Chapter 22: Encoding and Decoding Types

大綱

Encodable and Decodable protocols

  • Swift中encode和decodable的protocols

What is Codable?

  • Codable = Encodable + Decodable

Automatic encoding and decoding

  • 基本上, 所有在swift standard library的type都是Codable. ex. Int, Array, String, Date…

  • 任何Foundation framework中的type也是Codable。

  • 如果想要自己custom type也是Codable, 只要這個type中所有stored properties也是Codable, 那麼這個type也自動是Codable。

JSONEncoder and JSONDecoder

  • 一旦type是Codable, 就可以利用JSONEncoder, 將資料轉成data。

“By design, it’s specified at compilation time as it prevents a security vulnerability where someone on the outside might try to inject a type you weren’t expecting. It also plays well with Swift’s natural preference for static types.”

CodingKey protocol and CodingKeys enum

  • 利用CodingKey進行key的轉換

Manual encoding and decoding

  • 如果想要json進行格式轉換(非只是key轉換)

encodeIfPresent and decodeIfPresent

  • 如果當employees沒有 favorite toy就會導致轉成git產生null value。

Key points

  • You need to encode (or serialize) an instance before you can save it to a file or send it over the web.

  • You need to decode (or deserialize) to bring it back from a file or the web as an instance.

  • Your type should conform to the Codable protocol to support encoding and decoding.

  • If all stored properties of your type are Codable, then the compiler can automatically implement the requirements of Codable for you.

  • JSON is the most common encoding in modern applications and web services, and you can use JSONEncoder and JSONDecoder to encode and decode your types to and from JSON.

  • Codable is very flexible and can be customized to handle almost any valid JSON.

  • Codable can be used with serialization formats beyond JSON.

Last updated