Skip to content

Hi, my name is Jason.

When we speak about communication channel between our iOS app and web server – most of the times, it will be via REST architecture (check this post).
 
So, we send a request to our server, and it responds with some JSON. So, we need to parse that JSON into some objects (classes or structs). 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
typealias JSON = [String: Any]
typealias JSONArray = [JSON]
 
struct Model {
 
     // MARK: - Properties
     var name: String
     var height: String
 
     // MARK: - Initializer
     init(with json: JSON) {
          if let name = json["name"] as? String {
               self.name = name
          }
 
          if let height = json["height"] as? String {
               self.height = height
          }
     }
 
}

That’s just a lot of code. Imagine that we have like 20 properties. Terrible.
 
Enter Codable.
 
Apple introduced Codable protocol, which is an aggregation of Encodable & Decodable protocols. Idea is very simple – do not bother when you try to parse JSON.
 
Let’s see it in action:

1
2
3
4
5
6
7
8
9
10
struct Model: Codable {
 
     // MARK: - Properties
     var name: String
     var height: String
 
}
 
// Make a model object from Data which we acquired from the server
let model = try? JSONDecoder().decode(Model.self, from: data)

Is that it?
 
Absolutely.
 
Hmmm…
 
That is good, but what if I have an array of strings inside my model? You got me there.
 
Here is the solution: 

1
2
3
4
5
6
7
8
struct Model: Codable {
 
     // MARK: - Properties
     var name: String
     var height: String
     var films: [String]
 
}

Are you kidding me? No. It is really that easy. Swift is clever enough to figure out how to parse that array of strings.
 
What if I have some key in JSON which is not named as my property inside my struct? It’s a small update.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct Model: Codable {
 
     // MARK: - Properties
     var name: String
     var height: String
     var films: [String]
     var hairColor: String
 
     enum CodingKeys: String, CodingKey {
          case name
          case height
          case hairColor = "hair_color"
          case films
     }
 
}
 
// Make a model object from Data which we acquired from the server
let model = try? JSONDecoder().decode(Model.self, from: data)

That simple. You just put the correct value inside CodingKeys enum and voilà.
 
Can you imagine how clean your code can be with the usage of Codable protocol?
 
Hurry and fix it right away.
 
Happy coding!

Published iniOS

Be First to Comment

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: