Daniel's working notes

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

Linked Notes: