Codable Protocol with Any Type
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: 🧐
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.
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.
Below is the extension of AnyCodable enum with 2 methods to decode & encode Any type.
If any type value does not decode then it throws error. So we defined an error type enum to return specified error.
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. 😳
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.
Extension to cast the any type value to specifc primitive type.
So finally we done ✅
Complete code of AnyCodable
Summary
It’s time to play with ‘Any’ type ❤️
Thank You. Happy coding! 👍