您应该看一下 Swift4 Codable 协议。
为货币字典值创建一个符合 Codable 并具有相应属性的结构:
struct Currency: Codable {
let fifteenM: Double
let last: Double
let buy: Double
let sell: Double
let symbol: String
private enum CodingKeys: String, CodingKey {
case fifteenM = "15m", last, buy, sell, symbol
}
}
要解码 JSON 数据,您需要使用JSONDecoder
传递带有自定义值的字典[String: Currency]
作为要解码的类型:
let url = URL(string: "https://blockchain.info/ticker")!
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { return }
do {
let currencies = try JSONDecoder().decode([String: Currency].self, from: data)
if let usd = currencies["USD"] {
print("USD - 15m:", usd.fifteenM)
print("USD - last:", usd.last)
print("USD - buy:", usd.buy)
print("USD - sell:", usd.sell)
print("USD - symbol:", usd.symbol)
}
} catch { print(error) }
}.resume()
这将打印
1500 万美元:11694.03
美元 - 最后:11694.03
美元 - 买入:11695.01
美元 - 卖出:11693.04
美元 - 符号:$