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

Filtering a JSON array to display multiple or single key values

这个块允许我 select 一种货币和 return 模型中声明的所有 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)
}

我需要灵活性 return 只有一个值,例如 price。我可以注释掉该结构的所有属性,但价格除外,但这会限制功能。

有人告诉我可以将 let cryptocurrency = item.value.symbolreturn cryptocurrency == "ETH" 等进行比较,但我不确定如何完成此操作。

型号

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[[=12=].1.symbol] = [=12=].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
            }
        }

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

let ethPrice = rawResponse.data.filter({ [=10=].value.symbol == "ETH" }).first?.price

你把事情搞得太复杂了。

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

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

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

得到你想要的对象就是这部分

let item = rawResponse.data.filter({ [=12=].value.symbol == symbol }).first

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

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

for item in rawResponse.data {
    print("\(item.symbol) - \(item.price)"
}