Enum & custom type from primitive JSON type

with Swift Codable

Sarun W.
The OOZOU Blog
2 min readDec 18, 2018

--

Last year I wrote a review of Codable protocol in Swift 4 and how it competed with JSON encoder/decoder out there. I happy to say that Codable served me well over the year, so today I’m going to share some more use cases that I used throughout the year which also use Codable.

Enum

If your enum has a raw value that can be represented as Int or String (which I think that should cover most cases). We can make enum Codable by assigning a raw value to it.

Let’s say you have json object like this:

You can create Swift struct like this:

If you have enum which isn’t String or Int representable you can still make it conform toCodable as long as that raw value is Codable.

Custom type from primitive type

If you have custom type that can derived from basic JSON type, for example you have object with image sending as base64 encoded string:

Since UIImage doesn’t conform toCodable and we can’t conform it with an extension, we have 2 ways to handle this:

  1. Create another wrapper class around this image.

Code above should be familiar to you with one key take away.

Instead of :

we use:

since we are dealing with one primitive value, base64 string, in this case.

Then we can use this wrapper like this:

2. Add custom encode/decode for UIImage in KeyedEncodingContainer :

And use this with explicit encode and decode.

These 2 approaches should suffice for most of your use cases.

--

--

Sarun W.
The OOZOU Blog

iOS Developer at Oozou — Code & design iOS app — Follow me on https://twitter.com/sarunw for everything iOS — Blogging weekly at http://sarunw.com