Search code examples
iosswiftstruct

Dynamically change API data fetching structure


I am fetching data from an API that keeps changing it's format several times a day from String to Double erratically..

Is it possible to do something to the struct to prevent returning nil when fetching and automatically using with the right type?

    struct BitcoinGBP : Decodable {
    let price : Double
    let percentChange24h : Double

    private enum CodingKeys : String, CodingKey {
        case price = "PRICE"
        case percentChange24h = "CHANGEPCT24HOUR"
    }
}

Would simply using Double? work?


Solution

  • Write a custom initializer to handle both cases

    struct BitcoinGBP : Decodable {
        let price : Double
        let percentChange24h : Double
    
        private enum CodingKeys : String, CodingKey {
            case price = "PRICE"
            case percentChange24h = "CHANGEPCT24HOUR"
        }
    
        init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            percentChange24h = try container.decode(Double.self, forKey: .percentChange24h)
            do {
                price = try container.decode(Double.self, forKey: .price)
            } catch DecodingError.typeMismatch(_, _) {
                let stringValue = try container.decode(String.self, forKey: .price)
                price = Double(stringValue)!
            }
        }
    }