Upgrade to Pro — share decks privately, control downloads, hide ads and more …

値オブジェクトのCodable対応

maguhiro
September 06, 2019

 値オブジェクトのCodable対応

iOSDC Japan 2019のルーキーズLT枠で発表した資料です。

maguhiro

September 06, 2019
Tweet

Other Decks in Programming

Transcript

  1. struct User: Codable { let id: Int let name: String

    let age: Int } let json = """ { "id" : 1234, "name" : "maguhiro", "age" : 34 } """.data(using: .utf8)! let user = try! JSONDecoder() .decode(User.self, from: json) print("\(user.id)") // 1234
  2. class UserRepositoryImpl { func find(_ userID: Int) -> User? {

    // Կ͔͠Β͔ΒσʔλΛऔಘͯ͠ฦ٫ return user } } let userID = 1234 let photoID = 1000 let user = UserRepositoryImpl().find(photoID) // ↑ޡͬͯࣸਅIDΛҾ਺ʹ౉ͯ͠͠·͍ͬͯΔ
  3. struct UserID: Codable { let value: Int init(value: Int) {

    self.value = value } } struct User: Codable { let id: UserID let name: String let age: Int }
  4. class UserRepositoryImpl { func find(_ userID: UserID) -> User? {

    // Կ͔͠Β͔ΒσʔλΛऔಘͯ͠ฦ٫ return user } } let userID = UserID(value: 1234) let photoID = 1000 let user = UserRepositoryImpl().find(photoID) // ↑ޡͬͯࣸਅIDΛҾ਺ʹ౉͢ͱɺҎԼͷΑ͏ͳΤϥʔ͕ൃੜ͢Δ // Cannot convert value of type 'Int' to expected argument type 'UserID'
  5. let json = """ { "id" : 1234, "name" :

    "maguhiro", "age" : 34 } """.data(using: .utf8)! let user = try! JSONDecoder() .decode(User.self, from: json) // Swift.DecodingError.typeMismatch(Swift.Dictionary<Sw ift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "id", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found a number instead.", underlyingError: nil))
  6. extension ValueObject { init(from decoder: Decoder) throws { let container

    = try decoder.singleValueContainer() let value = try container.decode(Value.self) self.init(value: value) } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(value) } var description: String { return value.description } static func == (lhs: Self, rhs: Self) -> Bool { return lhs.value == rhs.value } }
  7. let json = """ { "id" : 1234, "name" :

    "maguhiro", "age" : 34 } """.data(using: .utf8)! let user = try! JSONDecoder() .decode(User.self, from: json) print(“\(user.id)”) // 1234