I have a Codable struct that is used to decode incoming JSON. Unfortunately, sometimes one of its key's value is a string, and sometimes it is a float. I was able to cobble a couple of do/try/catch blocks below to get it to work, but is there a better way to handle this?
struct Project: Codable {
public let version: Float
init(from decoder: Decoder) throws {
var decodedVersion: Float = 1.0
do {
decodedVersion = try values.decode(Float.self, forKey: .version)
} catch {
do {
if let inVersion = try Float(values.decode(String.self, forKey: .version)) {
decodedVersion = inVersion
}
} catch {
throw error
}
}
version = decodedVersion
}
}