1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SwiftのCodableの使い方 超個人的メモ

Posted at

SwiftyJsonが便利だけど、Swift表標準機能であるCodableもそこそこ使いやすかったのでメモ

実践的ではないけど一番シンプルなCodableでjsonをinstanceに変換する例

structにCodableを継承させて、jsonをデータ変変換した後、JSONDecoder.decodeを使うだけ。
ただ、Codableで定義した型情報と、jsonの形が厳密に同じである必要がある。そのため、jsonのキーが一つでも欠けているとエラーになる。


var data = """
{
  "name": "Bob",
  "age": 20,
  "sex": "male",
}
""".data(using: .utf8)!

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

let users: User = try JSONDecoder().decode(User.self, from: data)
users // User(name: 1, age: 20)

実践的なCodableの使い方(jsonのキーが欠ける場合)

structを以下のようにclass変変更し、init関数内で初期化を行う。
純粋なswiftで書かれているので、分かりやすい。

var data = """
{
  "name": "Bob",
  "age": 20,
}
""".data(using: .utf8)!

class User: Codable {
  var name: String
  var age: Int
  var sex: String? // sexがjsonにない!

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? nil
        self.age = try container.decodeIfPresent(Int.self, forKey: .age) ?? nil
        self.sex = try container.decodeIfPresent(String.self, forKey: .sex) ?? nil
    }
}
let users: User = try JSONDecoder().decode(User.self, from: data)
users // User(name: "Bob", age: 20, sex: nil)

まとめ

SwiftyJsonと比べCodableもそんなに悪くない。

1
1
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?