Codable Protocol with Any Type

The Blue Prototype
3 min readOct 20, 2020

Hope, all of you are aware with the basic concepts of Codable Protocol. In this article, we will focus on Any Type data parsing only.

Get Started

Codable protocol does not parse Any type data automatically. If you use Any type then compiler reproduce an error: 🧐

Person
Any type Codable error

You have to code for it, write code for decode & encode. 🙄

Let’s start with example ✍️

We have a model object ‘Person’ with name & id where id type is not confirm, whether it can be Int type or it can be String type.

Person

Now lets parse Any type with own Encodable & Decodable. In the below enum, we have to defined the expected types of person’s id. Below is the enum with string and int type.

AnyCodable with types

Below is the extension of AnyCodable enum with 2 methods to decode & encode Any type.

AnyCodable with Enocde & Decode methods

If any type value does not decode then it throws error. So we defined an error type enum to return specified error.

Error type

We have successfully written the code to parse the Any type data.

How to use AnyCodable?

Let’s use AnyCodable type in person model object and see how it works. We have defined id of AnyCodable type. Now there is no compilation error. 😳

Use of AnyCodable

Now id is any type basically, so whenever we will use it, we have to type cast it into int or string as per our requirement. Let make it more easy to acces.

In the below image, we made the id to private property and created a new property ‘personId’ of string type to access it and written the getter & setter property for that.

Access of AnyCodable

Extension to cast the any type value to specifc primitive type.

Type cast from Any to Primitive type

So finally we done ✅

Complete code of AnyCodable

Summary

It’s time to play with ‘Any’ type ❤️

Thank You. Happy coding! 👍

--

--