Now, let’s go again. 🧐

“Codable” is a protocol that helps us convert JSONs into objects and objects into JSON structures. The structures (struct) or classes (class) we will use must implement this protocol in order to perform these operations.

I suppose, you know what is JSON. If no, then let me know in comments and I can share another article about it. :)

Before practical exercises, let me give you a little bit of theoretical information about Encodable and Decodable.

Encodable:

  • The classes or structs that accept this protocol have the ability to convert themselves to JSON format. This process is completely automatic and quite magical.

Decodable:

  • Classes or structs that accept this protocol can create objects of their own type using JSON type data.

Now, let’s see how they work. I will share some examples in below, you can check, copy, paste and change them to understand the topic better.

Example for Encodable:

Let’s imagine that we have a struct named ‘User’. Getting this struct to accept the Encodable protocol is as simple as the following.

Let’s create an object from this struct and convert it to JSON format using the JSONEncoder class.

Example for Decodable:

Let’s imagine that we have a JSON file like the one below. This type of data is usually transmitted by the server to our application.

{  
"Brand": "Cadillac",
"Model": "Escalade",
"Year": 2022
}

Let’s assume that there is a struct named Inventory in our application and the JSON transmitted to us actually refers to an Inventory object.

Creating an Inventory object from the JSON data is as simple as this:

BONUS: Codable

  • Codable is a combination of Encodable and Decodable protocols. Classes and structs that accept this protocol accept both Encodable and Decodable protocols at the same time.

Basically that is all from my side. If you like my articles, if you think that they are useful, you can click on “Follow” button and share articles to reach more people. :)

--

--

Mammadowr

I speak 6 human and 5 programming languages. 🥳  iOS Developer. To support me: https://www.buymeacoffee.com/mammadowr8 ☕️