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

Swift 4から実装されるCodable/codable_in_foundation_wit...

fromkk
June 14, 2017

Swift 4から実装されるCodable/codable_in_foundation_with_swift4

What’s New in Foundation[212]というセッションで発表されたCodableというプロトコルに凄く感動したので発表してきました。

fromkk

June 14, 2017
Tweet

More Decks by fromkk

Other Decks in Programming

Transcript

  1. ؆୯ʹݴ͏ͱܾ·ͬͨϑΥʔϚοτͷDataܕ͔Β Codable ʹ४ ڌͨ͠ܕʹม׵͠΍ͯ͘͘͢͠ΕΔ΋ͷ public protocol Encodable { public func

    encode(to encoder: Encoder) throws } public protocol Decodable { public init(from decoder: Decoder) throws } public typealias Codable = Decodable & Encodable
  2. ࢖͍ํ let jsonString = """ { "name": "AKIBA.Swift", "date": "2017-06-13T19:00:00+0900",

    "place": "Classmethod" } """ guard let jsonData: Data = jsonString.data(using: .utf8) else { fatalError() } struct Event: Codable { let name: String let date: Date let place: String } do { let decoder: JSONDecoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 let event = try decoder.decode(Event.self, from: jsonData) print(event) //Event(name: "AKIBA.Swift", date: 2017-06-13 10:00:00 +0000, place: "Classmethod") } catch { print(error) }
  3. !

  4. ωετ΋ग़དྷΔ let jsonString = """ { "name": "AKIBA.Swift", "date": "2017-06-13T19:00:00+0900",

    "place": "Classmethod", "organizers": [ {"name": "Danbo"}, {"name": "Koumei"}, ] } """ struct Event: Codable { let name: String let date: Date let place: String struct Organizer: Codable { let name: String } let organizers: [Organizer] }
  5. Ωʔ໊͕ҧͬͯ΋େৎ෉ let jsonString = """ { "user_id": 12345, "created_at": "2017-06-03T10:00:00+0900",

    "updated_at": "2017-06-03T10:00:00+0900" } """ struct User: Codable { let userId: Int let createdAt: Date let updatedAt: Date private enum CodingKeys: String, CodingKey { case userId = "user_id" case createdAt = "created_at" case updatedAt = "updated_at" } }
  6. ͦͷଞ • struct Λ Data Խͯ͠ϩʔΧϧʹอଘͨ͠Γ෮ݩͨ͠Γͱ͍ ͏ࣄ΋؆୯ʹͳΔ • dateDecodingStrategy ʹ

    .formatted Λར༻͢Ε͹೔ ෇ͷಠࣗύʔεػೳ͕࡞ΕΔ • Encoder ϓϩτίϧΛద߹͢Ε͹ಠࣗEncoder͕࣮૷ग़དྷΔ • Decoder ϓϩτίϧΛద߹͢Ε͹ಠࣗDecoder͕࣮૷ग़དྷΔ ࢀߟ