Update

 avatar
unknown
swift
3 years ago
1.4 kB
8
Indexable

let json = """
{
  "ethereum": {
    "usd": 4079.65,
    "usd_market_cap": 485046321807.6035,
    "usd_24h_vol": 10367190648.654655,
    "usd_24h_change": 1.1217823683083594,
    "last_updated_at": 1640578355
  },
  "tether": {
    "usd": 1,
    "usd_market_cap": 77946024082.05913,
    "usd_24h_vol": 43358623503.14818,
    "usd_24h_change": -0.38108945958255486,
    "last_updated_at": 1640578408
  },
  "moonriver": {
    "usd": 192.09,
    "usd_market_cap": 499588933.7671746,
    "usd_24h_vol": 20313702.82210406,
    "usd_24h_change": 6.137060603150346,
    "last_updated_at": 1640578507
  },
  "wmatic": {
    "usd": 2.89,
    "usd_market_cap": 0,
    "usd_24h_vol": 91534006.12339644,
    "usd_24h_change": 8.77934574426758,
    "last_updated_at": 1640578469
  }
}
"""
internal struct Coin: Decodable {
    internal let coinInfo: [String: CoinInfo]
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        coinInfo = try container.decode([String: CoinInfo].self)
    }
}

internal struct CoinInfo: Decodable {
    internal let usd, usd_market_cap, usd_24h_vol, usd_24h_change: Float
    internal let last_updated_at: Int
}

do {
    let data = try JSONDecoder().decode(Coin.self, from: json.data(using: .utf8)!)
    let coins = data.coinInfo
    let ethereumData = coins["ethereum"]
    print(ethereumData)
} catch let err {
    print(err)
}

Editor is loading...