Codable Containers

Updated 30 August 2021

Save

In this blog, we are going to talk about Codable Containers. Containers provide a hierarchal parsing mechanism for Encoder and Decoder Protocol. We will discuss this topic later in the blog but first, let’s take a quick look at Codable Protocol.

Codable

Codable is used for the conversion between Swift Data Types and an external representation like JSON, XML, etc. It was introduced with Swift 4.0. Codable is a type alias for the Encodable and Decodable protocols.

When a type conforms to a Codable Protocol then all its properties must conform to Codable Protocol. Let’s see the available types which conform to Codable Protocols.

BuildIn Codable Types

Bool, Int, Int(N), UInt(N), Float, Double, String, Raw Representable (enum), Optional, Array, Set, Dictionary

For Container Types i.e Array, Set & Dictionary if the type they contain confirms to Codable Protocol then they also conform to Codable Protocol.

AffineTransform, Calendar, CharacterSet, Data, Date, Decimal, IndexPath, IndexSet, NSRange, URL, UUID, CGFloat, CGSize, CGRect, etc

Benefits of Codable

Example

Let’s see an example of how Codable Works.

Codable Example
Codable Example

In the above example, as you can see we have created a dummy Employee JSON data and then we are prasing that JSON response and storing it in our Employee model. For using Codable protocol we make our model conforms to Codable protocol and then we are able to decode JSON data using JOSNDecoder and then we print the response using dump method.

Employee response

When we make our model conform to Codable the protocol then swift compiler-generated some code at compile time due to which JSONDecoder was able to parse the JSON response to our model. Let’s see what code the Swift Compiler generates and discuss it in detail.

Codable Compiler Generated Example
Codable Compiler Generated Example

As you can see in the above code Swift Compiler generated 3 things for our Employee struct. let talk about these 3 in detail one by one.

First is a private enum called CodingKeys which raw representation is a String and its conform to CodingKey protocol. This enum is used to provides a list of keys which is used for encoding and decoding. You can also rename your key using this enum. Below is an example of this.

Renaming CodingKeys
Renaming CodingKeys

Second is init(from:) throws use to encode external representation into swift data types. It uses CodingKeys to find and map value to its respective properties in struct.

Last is encode(to: ) throws use to convert the struct data in Data type.

Encoding Objects
Encoding objects

Swtiching Formats

We can also convert the format of camel case to snake case using the below-mentioned properties.

Now let’s come to the main topic i.e Codable Containers. Have you notice in both init(from:) throws and encode(to: ) throws function the first thing which we are doing is creating a container. Why did we create a container? Let’s talk about them.

Codable Containers

As I have told earlier, “Containers provide a hierarchal parsing mechanism for Encoder and Decoder Protocol”. They do this by providing 3 different types of Coding Containers.

This is used to parse Dictionary Representation

This is used to parse Array Representation

This is used to parse a Single Primitive value

In addition, swift uses these 3 types of containers to store the Codable data. And the encoding containers supports 3 types of values i.e

  1. nil
  2. Primitive
  3. Encodable Type

Let’s see a graphical representation of how the values are stored in the coding container.

When we encode this JSON then the manner in which the containers are going to be used is represented using the below-mentioned diagram.

Customizating Codable

Now we will look at how can we customize Codable. We can customize the codable by modifying it in 3 ways.

  1. CodingKeys
  2. init(from: Decoder)
  3. encode(to: )

Let’s look few examples for this.

 * Flatting the Nested JSON using Decodable
Flatting the Nested JSON using Decodable

In the above example, we use nestedContainer. In other words, we flatten the Nested JSON.

Nesting the flatten json
Nesting the flatten JSON

In the above example, we have Nested the flatten JSON. In other words, we have done reverse of the last example.

Thank you for reading this article. If you want to read more articles regarding iOS Development click here. And if you want to know more about Codable Containers then click here.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home