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

249b3122eee454c0a818bfe7851418e4?s=47 fromkk
June 14, 2017

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

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

249b3122eee454c0a818bfe7851418e4?s=128

fromkk

June 14, 2017
Tweet

Transcript

  1. Swift 4͔Β࣮૷͞ΕΔ Codable AKIBA.swift WWDCಛू

  2. Profile Kazuya Ueoka Timers inc.ͷiOSΤϯδχΞ Twitter: @fromkk Github: fromkk Qiita:

    fromkk
  3. ࢥ͍ग़ͦͷ1 • Apple Parkʹಥܸ͕ͨ͠ೖΕͳ͔ͬͨ

  4. ࢥ͍ग़ͦͷ2 • ৯΂෺͕ͱʹ͔͘Ͱ͔͍

  5. ࢥ͍ग़ͦͷ3 • Keynoteͷҝʹே5͔࣌ΒฒͿʢ7࣌ʹ͸ձ৔಺ʹೖΕͨͷͰפ ͞͸ҙ֎ͱେৎ෉ʣ

  6. ࢥ͍ग़ͦͷ4 • ϐϯόονूΊΔͷָ͗͢͠Δ↗

  7. What’s New in Foundation[212]ͱ͍ ͏ηογϣϯͰCodable ͱ͍͏ϓϩτίϧ͕ൃද

  8. ؆୯ʹݴ͏ͱܾ·ͬͨϑΥʔϚοτͷ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
  9. ରԠࡁΈEncoder JSON • JSONEncoder • JSONDecoder Plist • PropertyListEncoder •

    PropertyListDecoder
  10. ࢖͍ํ 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) }
  11. !

  12. ͪͳΈʹ

  13. ωετ΋ग़དྷΔ 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] }
  14. Ωʔ໊͕ҧͬͯ΋େৎ෉ 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" } }
  15. ͦͷଞ • struct Λ Data Խͯ͠ϩʔΧϧʹอଘͨ͠Γ෮ݩͨ͠Γͱ͍ ͏ࣄ΋؆୯ʹͳΔ • dateDecodingStrategy ʹ

    .formatted Λར༻͢Ε͹೔ ෇ͷಠࣗύʔεػೳ͕࡞ΕΔ • Encoder ϓϩτίϧΛద߹͢Ε͹ಠࣗEncoder͕࣮૷ग़དྷΔ • Decoder ϓϩτίϧΛద߹͢Ε͹ಠࣗDecoder͕࣮૷ग़དྷΔ ࢀߟ
  16. ·ͱΊ • Swiftͷ৽ػೳͳͷͰiOSͷόʔδϣϯʹറΓ͕ແ͍ʢSwift 4ͰϏϧυ͍ͯ͠Ε͹աڈͷOSͰ΋ར༻ग़དྷΔʣ • ίϯύΠϥ͕Ϛοϐϯά෦෼Λࣗಈతʹߦͬͯ͘ΕΔͷͰهड़ ྔ͕গͳ͍ʢ͜Ε͕ؾ࣋ͪѱ͍ͱ͍͏੠΋Ұ෦ฉ͖·ͨ͠ʣ • ͱ͸͍͑ݸਓతʹ͔ͳΓخ͍͠ػೳͷ1ͭͳͷͰੵۃతʹ࢖ͬͯ ͍͖͍ͨͱࢥ͍ͬͯ·͢!

  17. ͝੩ௌ͋Γ͕ͱ͏͍͟͝·ͨ͠!