I'm consuming a JSON api that returns every field as a string. However some of those string values actually represent a timestamp and a longitude and latitude (as separate fields).
If I specify these values as a Date and Doubles respectively it swift throws an error Expected to decode Double but found a string
Struct Place {
var created_at: Date?
var longitude: Double?
var latitude: Double?
}
I've seen some examples that seem to deal with Date formatting online, but I'm unsure what to do around the Double values?
I tried overriding init(from decoder:Decoder) but this still doesn't give the correct values:
e.g
init(from decoder:Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
longitude = try values.decode(Double.self, forKey: .longitude) //returns nil but using String works fine
}
I know I can extract the string and convert to a double like:
longitude = Double(try values.decode(String.self, forKey: .longitude))
But is there another way?
Furthermore, I actually have a number of other properties that convert fine, but by doing this work around for these 3 properties, I now have to add all the other properties in there which seems a bit redundant. Is there a better way to do this?