Search code examples
iosswiftalamofiredecode

How I can decode and access Double from JSON using Alamofire and Swift Decode


I try do decode and access specific exchange rate for specific currency using Alamofire and Swift decode:

this is my model:

    struct Listek: Codable {
    let base: String
    let date: String
    let rates: [String: Double]

    enum CodingKeys: String, CodingKey {
        case base = "base"
        case date = "date"
        case rates = "rates"
    }
}

this is Alamofire API call + decode

let apiToContact = "https://api.exchangeratesapi.io/latest"
    AF.request(apiToContact).responseJSON { (response) in
    print(response)
    guard let data = response.data else { return }
    do {
    let st = try JSONDecoder().decode(Listek.self, from: data)
        print (st.rates)
        print (st.base)
        print (st.date)

    }
    catch {
    print("error")
    }

So far so good, but I fail in accessing the single currency and its rate value. I would like declare a variable "JPYrate" with value of JPY rate from JSON. Can you please navigate me?


Solution

  • You can simply get the value corresponding to key JPY from rates Dictionary like so,

    let JPYrate = st.rates["JPY"]
    

    Also, there is no need to create enum CodingKeys, if the key names are same as the property names. So, your struct Listek looks like,

    struct Listek: Codable {
        let base: String
        let date: String
        let rates: [String:Double]
    }