Working with Codable in Swift
- One of the most common task as iOS developer is get the data from server then parse them so it can be presented nicely to user. On iOS we have Codable protocols that allow us to encode and decode data into standard format (e.g JSON or Property List)
- Usually you define Struct or Class to represent model you get from the network call (most commonly used is JSON)
- Then you create initializer which accept decoder as its arguments and start decoding data there.
- You can use custom decoding and encoding strategy such as automatically convert from snake_case which commonly found on JSON response into camelCase which we use as variable
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
- Or if you have other requirements, you can also create custom decoder for yourself.
- Usually when decoding response from server, the initialiser will be marked as Throwing function and you decode within do catch block
do {
let data = decoder.decode(Model.self, from: backendData)
// when we get the data, we could assign them to our UI
} catch let error {
// do something like showing alert or toaster to user
print(error.localizedDescription)
}
FAQ?
How do we parse when some key is missing or contain null value?
When a key from response is missing, we can use decodeIfPresent
method that will produce optional type of our model properties. If the key is missing, our property will be nil
References
- Encoding and Decoding Custom Types
- What’s New in Foundation - WWDC 2017
- JSON Parsing with Codable in Swift
- Parse JSON into struct / object using Decodable protocol
- Encoding and Decoding in Swift
- Decode and Flatten JSON with Dynamic Keys Using Decodable
- JSON Decoding in Swift with Codable: A Practical Guide
- Getting Started with Moya - Flawless iOS - Medium
Linked Notes:
Today I learn
I believe that we can learn something new everyday, that’s why I set this page to record what I learn during the day.