I have struct
that conforms to protocol Codable
. Some properties are decoded from JSON fields so I use the CodingKeys
enum for that. But there are few properties that are not in my JSON and I need to calculate them from decoded JSON properties. For example, if you get a Zip code
from JSON, I want to calculate City
from it.
I don't want City
to be an optional String. So I try to calculate it right after my Zip code
field is decoded from JSON.
struct Place: Codable {
var name: String
var zipcode: String
// ... Lot of other properties decoded from JSON
var city: String // This property has to be calulated after `zip code` is decoded
enum CodingKeys: String, CodingKey {
case name = "placeName"
case zipcode = "NPA"
// other properties from JSON
}
}
I've tried this solution to rewrite init(from decoder: Decoder)
. But that means I need to manually write each property I need to decode. As I have a lot, I would prefer to let default init decoder does it job, and then add my code to calculate City
.
Is there a way to do something like : call default init with decoder, then add some code ?
I was also thinking about computed property. But as calculating City
from Zip code is quite lot of code, I don't want that it is always computed.
I need something like :
init(from decoder: Decoder) throws {
// <- Call default init from decoder
city = CityHelper.city(from: zipcode) // quite heavy code in there
}