gpt4 book ai didi

json - 在 Swift 字典中使用键值映射索引位置

转载 作者:行者123 更新时间:2023-11-28 14:39:13 25 4
gpt4 key购买 nike

根据我的模型,我能够
print(crypto, name, price ?? 0.0, totalSupply ?? 0.0)
//BTC 比特币 7639.39 17070625.0
//ETH 以太坊 590.943 99826611.0
//所有 99 种货币

我被迫打印出 API 中的所有 99 种货币。我希望能够精挑细选特定货币。

字典“1”对应BTC,字典“1021”对应ETH。这些与“id”键相同,但它们具有相同的数值。

是否最好只找到“id”元素然后使用一个条件来判断键值对 “id”:1“id”:1027是否发现打印该字典中的所有值?我需要映射吗?一个简单的条件?

目标是控制选择一种货币,即ETH/1027并打印一行,最终将在稍后放置在某种表格中。< br/>比特币 |比特币 | 7639.39 | 17070625.0


Controller

for (crypto, base) in rawResponse.data {
if let name = base.name {
let price = base.quotes["USD"]?.price
let totalSupply = base.totalSupply
print(crypto, name, price ?? 0.0, totalSupply ?? 0.0)
}

}

JSON 模型

struct RawServerResponse : Codable {
var data = [String:Base]()

private enum CodingKeys: String, CodingKey {
case data
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let baseDictionary = try container.decode([String:Base].self, forKey: .data)
baseDictionary.forEach { data[$0.1.symbol] = $0.1 }
}
}

struct Base : Codable {
let name : String?
let symbol : String
let quotes : [String: Quotes]
}

struct Quotes : Codable {
let price : Double?
let volume24H : Double?
}

JSON

"data": {
"1": {
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"website_slug": "bitcoin",
"rank": 1,
"circulating_supply": 17069825.0,
"total_supply": 17069825.0,
"max_supply": 21000000.0,
"quotes": {
"USD": {
"price": 7663.22,
"volume_24h": 4898370000.0,
"market_cap": 130809824337.0,
"percent_change_1h": 2.1,
"percent_change_24h": 1.17,
"percent_change_7d": 2.17
}
},
"last_updated": 1527925172
},
"1027": {
"id": 1027,
"name": "Ethereum",
"symbol": "ETH",
"website_slug": "ethereum",
"rank": 2,
"circulating_supply": 99817109.0,
"total_supply": 99817109.0,
"max_supply": null,
"quotes": {
"USD": {
"price": 589.299,
"volume_24h": 1841640000.0,
"market_cap": 58822122295.0,
"percent_change_1h": 1.9,
"percent_change_24h": 0.93,
"percent_change_7d": -0.96
}
}

最佳答案

我实际上建议您使用不同的 API,因为这种响应格式看起来不太适合开发。但是,如果您必须使用它,可以通过以下快速修复来选择单个项目:

if let eth = data.filter({ (item) -> Bool in
guard let crypto = item.value as? Base else {
return false
}
return crypto.symbol == "ETH"
}).first {
print(eth)
}

if let btc = data.filter({ (item) -> Bool in
guard let crypto = item.value as? Base else {
return false
}
return crypto.symbol == "BTC"
}).first {
print(btc)
}

关于json - 在 Swift 字典中使用键值映射索引位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50660913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com