Codable is actually a combination of the Encodable and Decodable protocols. Encodable turns your model object's values into a different format such as JSON or a Plist, while Decodable does the opposite. Each protocol has just a single method. These methods will get called when you call encode
or decode
. Before we look at how to implement these methods ourselves, you will need to understand a few data types.
Looking at both Encodable's encode(to encoder: Encoder) throws
and Decodable's init(from decoder: Decoder) throws
on a surface level, we see that they have an Encoder
and a Decoder
argument respectively. They are both protocols, which are then adopted by JSONEncoder/Decoder
and PropertyListEncoder/Decoder
, and any custom encoder and decoder that you may create. Both encoders and decoders have essentially the same properties and methods. We'll look at the Decoder
's properties and methods below:
Properties:
codingPath
: Allow