1

I'm trying to decode my one of the json files however certain fields have multiple types, so, for example, I have the fat set to Float. In one file its a Float and in another its a String, now I cannot change these files in any way. Is there any way to keep my structure while also doing multiple types for a single variable?

struct TheRes: Codable {
    //blah
    let info: Info

    enum CodingKeys: String, CodingKey {
        case info 
    }
}

struct Info: Codable {
    let ingredients: Ingredients?

    enum CodingKeys: String, CodingKey {
        case ingredients
    }

}

struct Ingredients: Codable {
    let fatHundredGrams: Float?

    enum CodingKeys: String, CodingKey {
        case fatHundredGrams = "fat_100g"
    }
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
OCTAVIAN
  • 336
  • 5
  • 18
  • `extension Ingredients { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) do { let string = try container.decode(String.self, forKey: .fatHundredGrams) if let float = Float(string) { fatHundredGrams = float } else { throw NSError(domain: "Invalid string: \(string)", code: -1, userInfo: nil) } } catch DecodingError.typeMismatch(_, _) { fatHundredGrams = try container.decode(Float.self, forKey: .fatHundredGrams) }}}` – Leo Dabus Apr 04 '19 at 16:49

0 Answers0