Codable in Swift and iOS

Photo by Ravi Roshan on Unsplash

Prerequisites:

Terminology

Codable: A type alias for Decodable & Encodable that allows easy conversion to or from a serialised format (i.e. JSON)

The implementation: codable

A typical application takes data from an Endpoint and decoded into a Swift model. Now since structs typically represent data and are value types they are suitable for models (over class, although you need to make your own decision about this).

The implementation: codable snake_case

We shouldn’t really be using snake_case in Swift code, yet your backend developer (this isn’t you, is it?) thinks that it’s a great idea.

decoder.keyDecodingStrategy = .convertFromSnakeCase

The implementation: non-matching key names

We can have a JSON string detailed by the following:

let data = “””{“idforuser”: 1,“globalid”: 2,“usertitle”: “test”,“complete”: true}“””

The implementation: nested JSON

Parsing data using coding

If you need to convert a date from JSON into your struct model, the decoder has you covered

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let readableDateFormatter = DateFormatter()
readableDateFormatter.dateFormat = "M-dd-yyyy HH:mm"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)

Conclusion:

Look, in the world of software development there is one thing that you are likely to have to do repeatedly. That is, you will need to convert JSON data to Swift objects.

Extend your knowledge

The Twitter contact:

Any questions? You can get in touch with me HERE

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store