Swift – Codable Protocol

Like many obedient Apple developers, in 2014 I responded immediately and tried to jump on the Swift bandwagon only to find that version 1 had a long way to go. At this time, the main challenge was that most of libraries and/or APIs that I needed to use only existed in Objective-c. Or if the Swift version was available, it was so limited that it was almost not usable. So, I went back into hibernation and waited for version 2; hoping for lots of advancement. Each year thereafter saw a new release of Swift; version 2 in 2015; version 3 in 2016; and version 4 in late 2017.
As a result, the main challenge for me… and probably other developers is the fact that each release contained such extensive changes, that you almost have to relearn Swift with each release. Also, the transition from version 2 to version 3 was very challenging. Today, with version 4, I am learning Swift for the fourth time and I am hoping that it has reached a reasonably stable point and that the learning curve for Swift 5 won’t be so great.
That being stated, I started developing a new App using Swift and at several points, I was REALLY close to throwing in the towel and cutting back over to Objective-C. The relearning the language was very frustrating.  But in the traditional spirit of Never Give Up, Never Surrender, I forged onward. The main driver for this spirit, which was almost broken, was the introduction of Codable protocol in Swift 4.
Like most Objective-C developers, I have spent countless hours writing coders and decoders and/or writing countless lines of code in order to process JSON data returned by a service call. But, with the introduction of Codable protocol, this has completely changed… and for the better!

So, how does it work?

Simple. Starting with a very simple example, let’s say that you have the following JSON data:

{
      "id": 1,
      "name": "Jim Johnson",
      "username": "jjohnson"
}

You simply need to create a data structure that matches the expected data format. In this case, the data structure is equally simple:

struct NameData: Codable {
      var id: Int
      var name: String
      var username: String
}

Now that you have defined a data structure that matches the expected JSON data format, there are four lines of code required to parse the JSON data that is returned. This uses a very simple HTTP request for demonstration purposes. More than likely your actual HTTP request will be more complex, maybe a URLSession, but that level of code complexity is not needed to demonstrate how easy it is to translate JSON data using a Codable data structure.
// First, create the URL string to be used

let url = URL(string: “http://api.mysite.com/v1/getnamedata”)

// Request the data from your URL

let resultsData = try? Data(contentsOf: url!)

// Create a JSON decoder

let  decoder = JSONDecoder()

// Decode / parse the returned JSON data into the NameDataList array of NameData struct

let nameDataList = try? Decoder.decode(NameData.self, from: resultsData!)

That’s it. Now you can access your results data very easily using the data structure that you created. For example, assuming that you received an array of names data, you might do the following:

let rowData = nameDataList[0]
print(rowData.id, rowData.name, rowData.username)

Now, let’s take a look at a more complex JSON response, which will probably be more realistic to a typical JSON response that you might have to deal with. This response contains a nested array of data:

{
      "id": 1,
      "name": "Jim Johnson",
      "addresses": [
      {
            "type": "home",
            "street": "123 Street Road",
            "city": "Douglassville"
            "state": "PA"
            "zipcode": "19518-1234"
      },
      {
            "type": "work",
            "street": "456 New Road",
            "city": "Blue Bell"
            "state": "PA"
            "zipcode": "19422"
      }
}

The required data structures needed to manage the above data would be as follows:

struct NameData: Codable {
      var id: Int
      var name: String
      var addresses: [Address]
}
struct Address: Codable {
      var type: String
      var street: String
      var city: String
      var state: String
      var zipcode: String
}

Using the above data structures, you can now manage the JSON response data using the exact same four lines of code given in the simple example. The decode(NameData.self, from: resultsData!) statement does all of the heavy lifting for you. Behind the scenes it generates the mountain of encode and decode methods that you use to go blind writing and testing by hand.
I don’t know about you, but I definitely prefer to spend my development time solving interesting and challenging coding issues, rather than writing countless lines of boilerplate code. So, from this perspective, the new Codable protocol in Swift is a home run.
What’s that you say? You’re still not ready to commit to learning Swift? No problem. Take the high road for now, because Swift and Objective-C can be used interchangeably within the same project. I would strongly advise that you create any new projects as a Swift project rather than an Objective-C project though. It is a little more straightforward to integrate Objective-C into a Swift project as compared to integrating Swift into an Objective-C project. I have done both successfully but starting with Swift is the better path to take, in my humble opinion. Plus, you’re a step closer to transitioning over to Swift. So, this is a win-win in my mind.
GET STARTED

Share on

linkedin sharing button twitter sharing button

Ready to get started?

Enter your information to keep the conversation going.
Location image
4 Sentry Parkway East, Suite 300, Blue Bell PA, 19422

Email Image

info@anexinet.com

Phono Image610 239 8100


Location Image4 Sentry Parkway East, Suite 300, Blue Bell PA, 19422
Phono Image610 239 8100