I'm using the Decodable protocol to decode some json, but I've run into a problem:
I'm getting an answer back, where a longitude and a latitide can be either an interger (latitude = 0) if there's no geo location data added to the element, and a String (fx. latitude = "25.047880") if there's geodata available. Now when I decode the json, I don't know how to build my Struct, as the long and lat can't both be String and Int.. So I'm getting a decode error when fetching elements where both cases are represented.
Any suggestions about how to solve this? I've tried with "Any" as datatype, but this doesn't conform to the Decodable protocol
struct JPhoto: Decodable {
let id: String
let farm: Int
let secret: String
let server: String
let owner: String
let title: String
let latitude: String //Can both be Int and String
let longitude: String //Can both be Int and String
}
You need to write your own encoder/decoder. You can use an associated value enum to do this, using a switch statement to encode and the throwing/catching behaviour to decode:
Here's an example of encoding and decoding this
AngularDistance
type:And here's your struct rewritten: