Swift 4 includes a new way to generate & parse JSON using the
Codable protocol. It’ll get rid of some boilerplate, especially when the objects or structs in our code have a similar structure to the JSON that we use to talk to a web service. In many cases you’ll be able to avoid writing any code that explicitly parses or generates JSON, even if your Swift structs don’t exactly match the JSON structure. That means no more long, ugly
init?(json: [String: Any]) functions.
Codable can also replace use of
NSCoding when we want to serialize objects to write them to a file and read them back again. It can work with plists as easily as JSON and you can write your own custom encoders & decoders for different formats.
Today let’s look at the simple case of converting an object or struct in our code to & from JSON. Then we’ll see how it might be more complicated when the JSON doesn’t match the objects & structs that we’re using in our code. We’ll use structs below but everything is the same if you need to use classes.Read on →