Understanding and Extending Swift 4’s Codable

Understanding and Extending Swift 4’s Codable

The Codable protocols (Decodable and Encodable) were introduced to the Swift standard library with Swift 4.

[…]

Many programming tasks involve sending data over a network connection, saving data to disk, or submitting data to APIs and services. These tasks often require data to be encoded and decoded to and from an intermediate format while the data is being transferred. The Swift standard library defines a standardized approach to data encoding and decoding.

[…]

When I first started looking into the Codable protocols, I was thrown off by the fact that classes like JSONDecoder and PropertyListDecoder didn’t conform to the Decoder protocol. According to Apple’s (documentation), Decoder is “A type that can decode values from a native format into in-memory representations.” Importantly, a Decoder needs access to some data that it can convert into model objects. JSONDecoder does not have access to any data on its own, and can be used repeatedly for deserializing different objects. It contains the rules for how data is deserialized and can be thought of as a high-level decoder or a decoding format. Since Swift is open source, it’s possible to go look at how JSONDecoder is actually implemented and in doing so you can see that it actually creates a fileprivate class that conforms to Decoder in order to deserialize data. So does PropertyListDecoder.

[…]