How to use Encodable and Decodable in swift?

In real life, Encoding is nothing but convert data or information in an any intended format, In swift Encoding Protocol does the same. By using the Encoding Protocol, we can convert model data as a request parameter for an API call.

And decoding means converts data into a readable format. In Swift, we can convert JSON data received from web service into our object model. No need to parse data explicitly. We can directly use this model class/struct without parsing the array and dictionaries of the JSON response.

Before implementing encodable and decodable please look into this URL, this Url is having JSON response which contains USER data, every operation like calling API and parsing on the same URL.

Before Encodable and Decodable protocol

Before the launch of Encodable and Decodable protocol, SwiftyJSON was on peak in use. Apple launched Codable and Decodable for flexibility in Web API data binding in Swift. Let’s deep dive into how Encodable and Decodable Works.


Encoder In swift
Encoder In swift

By using the encoding protocol we can generate request parameters by Model Class / Struct.

Let’s create one instance model by using struct “User“, and conform this struct by Encodable protocol. So we can encode this whole user instance.

Coding key enum is used to alter the identity of the User object, Suppose we are eliminating the CodingKey enum block. In User Object user name key will be pass with userName, but by using the coding key enum property we can change and alter from userName to name.

Without use of coding keys: userName : “Rahul”

With use of coding keys: name : “Rahul”


By using the decoding protocol we can convert API response in Model Class / Struct. When done with API call decoding the response in terms of UserResponse object

Here is how userObjects will print in the console.

Here is full code of encoding and decoding.

Leave a Comment