Hi all 👋,
While checking my blog on Medium, I have noticed that I forgot to write an article about Swift Codable which is very important. Then, I have asked myself, what do I wait for?!
Let’s go! 🥳
But first, did you read my previous articles? If not, then I strongly advise you to check them as well:
- Important things that every iOS Developer should know + Book advise
- What is Reactive Programming | RxSwift + Bonus Books
- Async/await in Swift | What is it?!
- What is SwiftLint? — The trip to the Clean Code
- Grand Central Dispatch & DispatchQueue in Swift
- What is SOLID?! — Bonus DRY principle
- (Possible) Interview questions and answers for every junior iOS Developers
- 13 Git commands that you will need in your career — Cheat Sheet
- What is Lifecycle of ViewController? — iOS Development with Swift
- How to become a developer? || Why you should NOT become?
- Reference and Value types in Swift — What are they?
- Unit testing | Swift
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. :)