Codable enums in Swift

Swift Enums are a powerful tool, so a lot of iOS developers are using those on a daily basis. Today I would like to show how to implement the Codable protocol for most popular enums use cases.


Let’s start with simple, old-fashioned enum:

Simple enum codable

To make this enum codable we need to do nothing but to conform the Codable protocol. Codable is a protocol composition typealias:

typealias Codable = Encodable & Decodable

You can ask why I didn’t use the rawValued enum here. There is a simple answer; I would like not to make public (as rawValue) the implementation details of this protocol methods.

Codable enums in Swift
source: unsplash.com

Sign up for Untitled Kingdom newsletter

Fresh startup & app development infobites delivered to your inbox.

➡️Check our Privacy Policy⬅️

Going further

The real beauty and straight of the enums come with associated Type enums. Let’s check if it is possible to make this type of enums Codable.

Conform to the Codable protocol:

But can we handle the Optional associated values? The answer is YES, but we need to make one small modification.

Enum with associated optional codable

All we need to do is to make a different method while decoding the associated values: decodeIfPresent, which is very useful when working with optionals for Codable protocols.

Maybe you are wondering what was coded under the associtatedValue key for the nil value, let’s check in Swift repo:

So using the JSONEncoder under the associatedValue, we will get null saved, which you can check by getting the Codable.playground in my repo:

https://github.com/gregiOS/Playgrounds/

Thanks for reading! 🚀

Sign up for Untitled Kingdom newsletter

Fresh startup & app development infobites delivered to your inbox.

➡️Check our Privacy Policy⬅️

Read more from Unititled Kingdom:

0
0
Also tagged Digital Health

How much does it cost to develop a digital health app and why?

Klaudia Raczek

Klaudia Raczek

Marketer interested in startups. Building software for web & mobile apps for digital health, FemTech, IoT and digital transformation @ untitledkingdom.com

Klaudia Raczek

Klaudia Raczek

Marketer interested in startups. Building software for web & mobile apps for digital health, FemTech, IoT and digital transformation @ untitledkingdom.com

Feb 21, 2019 6 min read
Also tagged Business

What’s my purpose of running a business?

Also tagged Work Culture

Software company vs. digital product studio. What’s the difference? What questions should you ask?

Klaudia Raczek

Klaudia Raczek

Marketer interested in startups. Building software for web & mobile apps for digital health, FemTech, IoT and digital transformation @ untitledkingdom.com

Klaudia Raczek

Klaudia Raczek

Marketer interested in startups. Building software for web & mobile apps for digital health, FemTech, IoT and digital transformation @ untitledkingdom.com

Jan 07, 2019 9 min read