Swift AnyCodable

Karthik
3 min readAug 26, 2021

--

Let’s review the Anycodable framework to see what common pitfalls it tries to solve.

There is no direct way to decode a dictionary inside the codable object. AnyCodable framework by Tai Le helps in decoding any objects, So let’s review the framework with a real use case.

Use Case

Most of the applications do have a currentUser object, which could be of value type that persisted in either user defaults or keychain, in some cases we might want to store metadata information that could be of any type.
Eg: Dictionary, Array, Enum, etc.

Example AppUser with metadata

Serialization Rule

For successful serialization, all the properties under a codable object must be codable. Since metadata dictionary’s values could be of Any Type and the compiler doesn’t aware of the codable protocol conformance, it throws the following error.

When tried to check the list of APIs that swift offers for encoding the data, didn’t find any direct way of doing so.

Here comes the AnyCodable framework to the rescue. Let's see how the AnyCodable framework approaches this pitfall.

AnyCodable

This library facilitates encode and decode[String: Any], [Any]

AnyCodable opens two decode APIs which helps to serialize Array and Dictionary under the codable object. Under the hood, AnyCodingKey was used to construct the Nested KeyedDecodingContainer to initiate the decoding process. To meet the serialization rule, all keys were iterated to map with the concrete type. This helps the compiler to know the codable conformance of each property inside the codable object.

Let's apply the AnyCodable API to our CurrentUser Codable object for successful serialization.

As shown in Line No 16, id, email, and metadata dictionary were successfully serialized with the help of Anycodable decode API.

Lets Parse Metadata

Sometimes we might want to serialize metadata into a codable object. This is where we can make use of Native JSONSerialization to convert into a codable object if all the properties are confirming codable conformance.

Since MetaData object and its properties satisfy codable protocol conformance, we can serialize AppUser’s metadata dictionary into MetaData object with the help of Parse function.

let appUser: AppUser = AppUser()
let metadata: MetaData = appUser.metadata.parse()!

That’s it for this time! 👏👏👏 . Feel free to comment if you have questions and follow to get notifications about future articles.

“Be the senior engineer you needed as a junior.” — Someone

--

--

Karthik
Karthik

No responses yet