Swift: A better way to write Models using codable

Swift: A better way to write Models using codable

Apple recommends MVC architecture for development and is undeniably more common architecture. MVC segregate code in three parts – logic/data, view(GUI) and model. Today we’ll talk about how to write models while minimizing boilerplate code.

Models are representations of data that flows through your application. For example, we get unordered and unreadable junk from servers and that too in huge quantity. We know we have some edible data in the junk and we need a way to filter it out. Moreover model has knowledge of a domain(say User), user’s data is used multiple times in an application. Same user model can be used at all places.

Models are not concerned about UI and presentation of data and not even the logic behind operations. In simple words they are data containers, having data organized as objects with some properties. The view and the controller communicate with each other indirectly through these data containers(model).

To understand better lets talk some code.

Lets create a demo JSON having with object named organization and having three associated properties:

{
    "organization" : {
        "organization_name" : "IPHS technologies",
        "organization_location" : "Lucknow, India",
        "established_year":2012
      }
}

We will parse the JSON first using the conventional model approach. Next, we do the same task using Codables.

Old School Approach

Consider a Users model with some properties:

class Organization {
    orgName: String
    orgLocation: String
    established: Int
}

Organization has three properties – organization name of string type, organization location is again of string type. and established year of integer type.

Organization properties has to be  initialised. We will initialise it using init() method:

class Organization {
orgName: String
orgLocation: String
established: Int

init?(orgName: String, orgLocation: String, established: Int) {

// Initialize stored properties.
self.orgName = orgName
self.orgLocation = orgLocation
self.established = established

  }
}
view raw

Let’s see a use case of model: Let suppose we have response in JSON format from the server. We first have to parse JSON and set it in our model class.

var organization: Organization?
let jsonData: Data = /* get your json data from server or local json file */
let jsonArray = try [JSONSerialization.jsonObject(with: jsonData) as? [NSDictionary] let organizationName = jsonArray["organization_name"] as? String
let organizationLocation = jsonArray["organization_location"] as? String
let established = jsonArray["established_year"] as? Int
user(orgName: organizationName, orgLocation: organizationLocation, age: established)

That’s general way parsing json in models.
Now will do the same task but now using codable and will talk about the differences between these two approaches.

Cleaner Approach using codable

Codable is collective name given to protocols Encodable and decodable. In this demo we only need decodable. We write codable model as follows:

struct Organization: Decodable{
   organization_name: String
   organization_location: String
   established_year: Int
}

And thats it!.
Here, names of the parameters matches the json keys. If you want to follow your favorite naming convention then you can use coding keys. Coding keys helps you keep your code readable. You can implement coding keys like this

enum CodingKeys: String, CodingKey {
        case orgName = "organization_name"
        case orgLocation = "organization_location"
        case age
}

Now we will decode json data.

let jsonData: Data = /* get your json data from server or local json file */
let organization = JSONDecoder().decode(Organization.self, from: jsonData)
print("Organization Name: - \(organization.orgName) \n")
print("Organization location: - \(organization.orgName) \n")
print("Year of foundation: - \(organization.established)")

Above snippet simply prints parsed data on console. The output looks like this

Organization Name: - IPHS Technologies
Organization location - Lucknow, India
Year of foundation: - 2012

Decodable, clearly is winner if we compare above two approaches of JSON parsing.

Please follow and like us:

Leave A Comment

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