LoginSignup
1
1

More than 5 years have passed since last update.

Codableを使うときの注意点。

Last updated at Posted at 2019-04-08

Data(json)

let jsonData = """
  {
    "name": "太郎",
    "age": 20
  }
  """.data(using: .utf8)!

この時に大事なところは
.data(using: .utf8)!
です。これがないと変換できないとエラーが出ます。

これを使わない場合は

let decodeData = jsonData.data(using: .utf8)

などで"utf8"に変換しないといけません。
そして、デコードする構造体Structを定義します。プロトコルでCodableもしくはDecodableを指定することを忘れずに!

struct Peaple: Codable {
    let name: String
    let age: Int
}

Decode

実際にデコードします。

let decodeData = try! JSONDecoder().decode(Peaple.self, from: jsonData)

これで"decodeData"にデータ が格納されたはずです。

print(decodeData.name)

とすると、"太朗"と出力されます。

Swiftで行こう!--CodableでAPIを!

1
1
0

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
1
1