Fat Mike
Fat Mike

Reputation: 21

Swift codeable for date keys

I'm trying to do a codeable struct for a Financial API that returns

"Time Series (Daily)": {
        "2018-11-16": {
            "1. open": "190.5000",
            "2. high": "194.9695",
            "3. low": "189.4600",
            "4. close": "193.5300",
            "5. volume": "36928253"
        },
        "2018-11-15": {
            "1. open": "188.3900",
            "2. high": "191.9700",
            "3. low": "186.9000",
            "4. close": "191.4100",
            "5. volume": "46478801"
        },
        "2018-11-14": {
            "1. open": "193.9000",
            "2. high": "194.4800",
            "3. low": "185.9300",
            "4. close": "186.8000",
            "5. volume": "60800957"
        }
}

I can't use CodingKeys, as the keys are dates and they vary. Not sure how to tackle this.

Upvotes: 1

Views: 103

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100523

You can try

struct Root: Codable {

    let timeSeriesDaily: [String: TimeSeriesDaily] // make key as String to generalize all keys 

    enum CodingKeys: String, CodingKey {
        case timeSeriesDaily = "Time Series (Daily)"
    }
}

struct TimeSeriesDaily: Codable {
    let the1Open, the2High, the3Low, the4Close,the5Volume: String 
    enum CodingKeys: String, CodingKey {
        case the1Open = "1. open"
        case the2High = "2. high"
        case the3Low = "3. low"
        case the4Close = "4. close"
        case the5Volume = "5. volume"
    }
}

Upvotes: 1

Related Questions