Swift从中获取最大密钥并进行排序

时间:2018-09-18 08:34:40

标签: ios swift dictionary

我里面有var dataDictionary = [[String:Any]]()和数据:

[["quant": 10, "name": "..."], 
["quant": 20, "name": "..."], 
["quant": 25, "name": "..."],
["quant": 27, "name": "..."],
["quant": 30, "name": "..."],
["quant": 30, "name": "..."],
["quant": 20, "name": "..."],
["quant": 40, "name": "..."],
["quant": 15, "name": "..."],
...]

我想从所有“ quant”中获取最大值,然后创建func以对maxKey进行选择int并打印 例如,需要从30到maxKey并获取:

[["quant": 30, "name": "..."],
["quant": 30, "name": "..."],
["quant": 40, "name": "..."]]

我试图获得这样的最大值:

let maxVal = dataDictionary.max { a, b in a.value < b.value }

但是有错误

  

“ [String:Any]”类型的值没有成员“ value”

4 个答案:

答案 0 :(得分:1)

尝试

 dataDictionary.sort { (v1, v2) -> Bool in
  return v1["quant"] as? Int ?? 0 <  v2["quant"] as? Int ?? 0
}
let min = 30
let max = dataDictionary.last!["quant"] as? Int ?? min
let filtered = dataDictionary.filter({(dict) in
  let valueToCompare = dict["quant"] as! Int
  return valueToCompare >= min && valueToCompare <= max
})
print(filtered)

答案 1 :(得分:1)

您必须通过订阅访问"quant"值:

var dataDictionary = [[String:Any]]()
let maxVal = dataDictionary.max { (lhs, rhs) -> Bool in
    let leftValue = lhs["quant"] as? Int ?? 0
    let rightValue = rhs["quant"] as? Int ?? 0
    return leftValue < rightValue
}

答案 2 :(得分:0)

您正在max上进行array,因此您必须像这样通过keyValue pair访问quant:

    dataDictionary.max { (a, b) -> Bool in
        return a["quant"] as! Int > b["quant"] as! Int
        //Or with optional
        return a["quant"] as? Int ?? 0 > b["quant"] as? Int ?? 0

     }

[String: Any]上进行操作时,OtherWise可以像您一样进行操作

let greatestDict = dataDictionary.max { a, b in a.value < b.value }
print(greatestDict)

答案 3 :(得分:0)

在您尝试过的机制中,

let maxVal = dataDictionary.max { a, b in a.value < b.value }

a,b是[String: Any]类型的字典,不具有.values属性。因此,要找到最大量化字典,您应该使用:

let maxVal = dataDictionary.max { a, b in (a["quant"] as! Int) < (b["quant"] as! Int) }

如果希望获取所有具有大于或等于特定值的定量的字典,则必须使用:

let quantLimit: Int = 30
let maxValFrom30 = dataDictionary.filter({ ($0["quant"] as! Int) >= quantLimit })