name: String var points: Int var description: String? } let json = """ { "name": "Durian", "points": , "description": "A fruit with a distinctive scent." } """.data(using: .utf )! let decoder = JSONDecoder() let product = try decoder.decode(GroceryProduct.self, from: json) print(product.name) // Prints "Durian"
Codable { var name: String var points: Int var description: String? } let json = """ { "name": "Durian", "points": , "description": "A fruit with a distinctive scent." } """.data(using: .utf )! let decoder = JSONDecoder() let product = try decoder.decode(GroceryProduct.self, from: json) print(product.name) // Prints "Durian"
and out of an external representation. • 今回はJSON • 標準の型はもちろんCodableに準拠するデータ構造で フィールドを構成していればCodableにできる • OptionalにすればJSONのnullもマッピング可能 Codableとは 14 struct GroceryProduct: Codable { let name: String let points: Int let description: String? let myStruct: MyStruct } struct MyStruct: Codable { var name: String } let json = """ { "name": "Durian", "points": , "description": "A fruit with a distinctive scent." "myStruct": { "name": "Durian" } } """.data(using: .utf )!
let name: String let points: Int enum CodingKeys: String, CodingKey { case name case points } enum AdditionalCodingKeys: String, CodingKey { case usingOnlyDecode } } init(from decoder: Decoder) のみで利⽤ encodeは ⾃動推論してくれる