Search code examples
jsonswiftdecodable

How to decode custom type inside dictionary value with JSON?


my JSON:
https://www.cbr-xml-daily.ru/daily_json.js
my code:

struct CoinData: Decodable {
    let Valute: [String: CoinInfo]
}

struct CoinInfo: Decodable {
    let Name: String
    let Value: Double
}
if let safeData = data {
    if let coinData = self.parseJSON(safeData) {
    print(coinData) 
    }
}
func parseJSON(_ data: Data) -> [String: CoinInfo]? {

    let decoder = JSONDecoder()
     do {
        let decodedData = try decoder.decode(CoinData.self, from: data)
        return decodedData.Valute

     } catch {
        delegate?.didFailWithError(error: error)
        return nil
    }
}

In debug console following gets printed:

["PLN": CurrencyConverter.CoinInfo(Name: "X", Value: 19.6678), ...]

This way I can't reach Name and Value properties of a coin. What's wrong?


Solution

  • I am going to do for-loop to check if a key contains certain symbols. If it does - I will need to be able to access to both Name and Value

    You don't actually need a for loop. Since coinData is a dictionary, you can use its subscript, together with optional binding to do this. For example, to check if the key "PLN" exists, and access its name and value:

    if let coinInfo = coinData["PLN"] {
        print(coinInfo.Name)
        print(coinInfo.Value)
    } else {
        // "PLN" does not exist
    }