The easy way to parsing JSON with Swift 4

We’ve all been there.

A new project is starting up, there are new APIs to consume and lots of JSON to go along with them.

JSON libraries have been something of a favorite pastime for the Swift developer, ever since the language popped up three years ago.

There are literally dozens of libraries to choose from.

Well, the fine folks at Swift have taken notice and thus the SE-0167 proposal was born.

SE-0167 or more popularly known as the Codable protocol is actually two protocols, that working alongside the new compiler, enable an easy and powerful new way to encode and decode data.

What does that look like?

Say that we get the following JSON from our server:


And we have the struct that’ll contain our data defined as such


In the past the evil that all of the JSON parsers tried to get us rid of would’ve looked like so:


All of the casting, stringly typed accessors and ignoring that the Date object would just fail without further tinkering, made for an abysmal experience requiring you to provide your own initializers that’ll accept the end result or worse – include this code in your model objects.

The Codable protocol comes to our aid to solve the issue just by implementing it like so.


It’s easy as that, no stringly typed API, no formatting of dates.

The compiler automatically generates the parsing implementation at compile time and as long as the JSON keys match your variables all is well.


Custom JSON keys

But what if your API returns something like this?

It’ll hurt legibility, if you have to change your variable names, so that they match whatever JSON keys the API returns.

Luckily there’s a way to customize that.

The compiler generates a nested enum in each class called CodingKeys which handles how the JSON parsing is done.

It looks like this.


We can take advantage of the enum and change the case for our releaseDate variable, so that we can keep the awesome name that we’ve chosen and still take advantage of the new functionality.


Handling arrays

This all seems awesome, but what if we have a bunch of these objects?


Again, it’s really easy, we just change the type of the object that we’d like to decode.


There’s a lot more that we can do with the Codable protocol, like handling data, custom date formats, nested structures and customizing.

If you’d like to learn more, visit the Ultimate Guide by Ben Scheirman.

1 Comment

  1. your code is not working. I got this error :

    error: use of unresolved identifier ‘str’
    let jsonResponse = .utf8)

    you are using “str” without creating it. also how can I set json string to variable ?


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.