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:
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.
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
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:
Thanks for reading! 🚀