Swift 4 lets you serialize your custom data types to JSON without writing any special code.
You can see I’ve marked the
Language struct as conforming to the
Codable protocol. With that one tiny addition, we can convert it to a
Data representation of JSON like this:
Swift will automatically encode all properties inside your data type – you don’t need to do anything.
Now, if you’re like me and have a long history of using
NSCoding, you’re probably somewhat doubtful: is that really all it takes, and how can we be sure it’s working? Well, let’s add some more code to try converting the
Data object into a string so we can print it out, then decode it back into a new
Language instance that we can read from: