LoginSignup
9

More than 5 years have passed since last update.

SwiftでplistをCodableで読み込む

Last updated at Posted at 2018-06-20

SwiftでplistをCodableで読み込む

昨日の記事Swiftでplistを読み込むに「NSDictionary使いたくない」って書いたら心優しいmasakihoriさんが Whisper words of wisdom 「Codeableで書けばええ」をくださった、、、ので早速トライした。

実行環境は前回と同じ(2018年6月20日現在 xcode 9.4.1, swift 4, ios 11.4)

結論

Codable のほうが絶対いいよね。かっこいいし。

コード

Codable protocolをもつApiURL構造体をつくりました。
classでも使えるんか?って思って試しましたが使えません。
いや、正確には使えるかもしれませんがおそらく使い物になりません。

ApiCodable.swift
struct ApiURL: Codable {
    let BaseURL: String
    let Paths: ApiPaths
}

struct ApiPaths: Codable {
    let user: Dictionary<String, String>
    let staff: Dictionary<String, String>
}

そして以下のコードで plist をデコードします。propは構造体なので.(ドットシンタックス)でメンバにアクセスできます。 
すごく便利です。

AppDeligate.swiftとか
var prop: ApiURL?
if let urls = Bundle.main.path(forResource: "ApiURL", ofType:"plist" ) {
  do {
    let data  = try Data(contentsOf: URL(fileURLWithPath: urls))
    self.prop = try PropertyListDecoder().decode(ApiURL.self, from: data)
  } catch let e {
    print("Failed to getting properties from plist.")
    print("Reason: \(e)")
  }
}
prop?.BaseURL // -> "https://api.example.com"

一言メモ

Codableはswift4で追加されましたが、かなりの発明品だと思う。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9