过滤JSON数组以显示多个或单个键值

问题描述 投票:2回答:1

此块允许我选择单一货币并返回模型中声明的所有API值。 idsymbolnamepricemarketCap等。

接口

let data = rawResponse.data
if let eth = data.filter({ (item) -> Bool in
   let cryptocurrency = item.value.symbol
   return cryptocurrency == "ETH"
}).first {
   print(eth)
}

我需要灵活地只返回一个值,如price。除了价格,我可以注释掉结构的所有属性,但这限制了功能。

我被告知我可以将let cryptocurrency = item.value.symbolreturn cryptocurrency == "ETH"etc进行比较,但我不知道如何做到这一点。

模型

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 id : Int?
    let name : String?
    let symbol : String
    let quotes : [String: Quotes]
}

struct Quotes : Codable {
    let price : Double?
}

JSON

"data": {
    "1027": {
        "id": 1027, 
        "name": "Ethereum", 
        "symbol": "ETH", 
        "website_slug": "ethereum", 
        "rank": 2, 
        "circulating_supply": 99859856.0, 
        "total_supply": 99859856.0, 
        "max_supply": null, 
        "quotes": {
            "USD": {
                "price": 604.931, 
                "volume_24h": 1790070000.0, 
                "market_cap": 60408322833.0, 
                "percent_change_1h": -0.09, 
                "percent_change_24h": -2.07, 
                "percent_change_7d": 11.92
            }
        }
json swift codable
1个回答
2
投票

要过滤数组并显示单个值(或者在您的情况下找到以太坊并使用价格),您可以执行以下操作:

let ethPrice = rawResponse.data.filter({ $0.value.symbol == "ETH" }).first?.price

你太复杂了。

如果这需要是动态的,你可以将它放在一个函数中

func getPrice(symbol: String) -> Double? {
    return rawResponse.data.filter({ $0.value.symbol == symbol }).first?.price
}

你需要考虑你在较小的工作中所做的事情。

获取您想要的对象是哪个部分

let item = rawResponse.data.filter({ $0.value.symbol == symbol }).first

然后,您可以访问该对象的所有属性。

如果你想打印所有项目的名称和价格,你也可以很容易地做到这一点

for item in rawResponse.data {
    print("\(item.symbol) - \(item.price)"
}
© www.soinside.com 2019 - 2024. All rights reserved.