Be default, Decodable
protocol makes translation of JSON values to object values with no change. But sometimes you need to transform value during json decoding, for example, in JSON you get {id = "id10"}
but in your class instance you need to put number 10
into property id
(or into even property with different name).
You can implement method init(from:)
where you can do what you want with any of the values, for example:
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
latitude = try container.decode(Double.self, forKey:.latitude)
longitude = try container.decode(Double.self, forKey: .longitude)
// and for example there i can transform string "id10" to number 10
// and put it into desired field
}
Thats sounds great for me, but what if i want to change value just for one of the JSON fields and left all my other 20 fields with no change? In case of init(from:)
i should manually get and put values for every of 20 fields of my class! After years of objC coding it's intuitive for me to first call super's implementation of init(from:)
and then make changes just to some fields, but how i can achieve such effect with Swift and Decodable
protocol?
init(from:)
method for all the properties anyway? – MorganiteStringCodableMap
didn't implementinit(from:)
; they relied on the auto-generatedCodable
conformance. – Circumspection