Swift Codable: tips and tricks

Let’s dive into Codable to see what are the benefits of migrating from your third-party json library.

Mario Iannotta
Sep 23, 2017 · 4 min read

What is Codable?

If you take a look into the Codable definition you’ll find out that it’s just a way to tell that something is Decodable and Encodable.

Why is it a game changer?

Today every App is connected with web services and most of them provide data using the JSON format for its ease of reading and generating for both humans and machines.

Simple usage

Suppose we want to know some basic information about this post and the Medium API give us something like this:

Nested objects

Nothing changes with nested object, the only think you need to remember is that even the nested objects need to conform the Decodable protocol and need to provide a custom init where needed.

Flatten nested objects

When we have a nested JSON but we want to flatten it into one single object we could use the function nestedContainer(keyedBy: forKey:)

Dynamic keys

Sometimes we don’t want to have fixed values for our coding keys but we want to be able to build them at run time. This is possible using a concrete implementation of the protocol ConcreteCodingKeys

To infinity and beyond

  • Automatching” is only available with type values such as struct, if you want your class to work with Codable you have to always provide a custom init.
  • You can decode array and dictionary as well, just use decoderContainer.decode([YourObjectInAnArray].self, from: jsonData) for array and decoderContainer.decode([YourKey: YourObjectInArray].self, from: jsonData)for dictionaries.
  • If you need a custom coder in addiction to JSONCoder and PropertyListCoder you can write your own!

Download

You can download here a playground where you can find a lot of examples of decoding simple and complex objects.

Conclusions

Using Codable instead of a third-party library (such as Marshal or SwiftyJSON) could look tricky at the beginning but after a some pratice you’ll able to achieve anything you want with (usually) less code and since you’re using a part of the standard SDK your app will weight less.

Mario Iannotta

Written by

iOS Developer, tech enthusiast