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: “://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.

James Johnson
Senior Consultant
Jim Johnson is a Senior Consultant with over three decades of IT and management experience, and ten iOS apps in the App Store. An experienced developer focusing on Native Apple technologies, Jim has worked in the Pharmaceutical, Healthcare, Life Insurance, Furniture, Energy and Manufacturing industries. He holds a Master’s degree in Business Management from Saint Joseph’s University. during 2014 received his Certified Scrum Master certification.
Let’s get the conversation started
Reach out now to begin your digital transformation
+ 16,659
ZOOM MEETINGS
+ 9,789
HAPPY CLIENTS
+ 5,075
FINISHED PROJECTS
+ 133,967,432
LINES OF CODE
© 2000 - 2021 Anexinet Corp., All rights reserved | Privacy Policy | Cookie Policy
This website uses cookies
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL cookies.
Manage consent
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie | Duration | Description |
---|---|---|
cookielawinfo-checbox-analytics | 11 months | This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics". |
cookielawinfo-checbox-functional | 11 months | The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional". |
cookielawinfo-checbox-others | 11 months | This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other. |
cookielawinfo-checkbox-necessary | 11 months | This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary". |
cookielawinfo-checkbox-performance | 11 months | This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance". |
viewed_cookie_policy | 11 months | The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data. |
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.