Parsing using Codable

February 11, 2018

In this article on iOSTLDR I will be writing about how to make use of the Codable protocol, a protocol introduced in swift 4 for serialisation of data,  IMO It is a very good addition from apple and eliminates (almost) the need to use of third party libraries such as Mantle or ObjectMapper for this reason.


so suppose we have a response for a photo object like this one :



a corresponding Codable struct would be:



and it can easily be decoded by:

see how fast is it ? Codable provide an automatic serialisation without need for specifying mapping keys if the properties keys are the same of the response and types which are either: StringInt, Float, Double, URL or containers consisting of one of them or Codable conformed objects.


Codable is a typealias of Encodable & Decodable protocols, which are one of the latest additions in Swift 4 to enable easy decoding and encoding of data, More about them later.


It is worth to note that Automatic serialisation is done If the keys are camelCased but in case of snake_cased convention, there are some good news as starting Swift 4.1 is handled by an amazing addition -> `KeyDecodingStrategy`, where the decoder can specify to use the snake cased convention


so in case of a response similar to this one 

Automatic serialisation is possible through:


In some cases , it would be required to make mappings from keys to properties, this is achievable through the implementation of "enum CodingKeys ", so for a response like the one below 

would have a corresponding struct of 

 For full manual parsing, the implementation of Decodable protocols functions is required such as


For models generation, A generation tool such as this one is recommended, nevertheless it is highly recommendable to to go through the models generated for more customisation and omitting of non-needed properties, this would definitely spare some good time in general and make life easier.



Share on Facebook
Share on Twitter
Please reload

Mindmap for Mobile Apps dev. environment

February 17, 2019

iOS SNAPSHOT Testing Usages

January 11, 2019

Please reload

This site was designed with the
website builder. Create your website today.
Start Now