我有一个字典数组,需要检查一个键值对是否存在,如果不返回默认值。
使用下面的代码,我可以找到一个键值对(如果存在)。
let arrayOfDicts = [["Name": "JW", "amount": 50], ["Name": "Red Wine", "amount": 50], ["Name": "White Wine", "amount": 50], ["Name": "X", "amount": 50], ["Name": "JW", "amount": 50], ["Name": "Y", "amount": 50], ["Name": "Y", "amount": 50]]
let nameToFind = "Smirnoff"
var amount = ""
for i in 0..<arrayOfDicts.count{
if arrayOfDicts[i]["ingredient"] as! String == nameToFind {
amount = arrayOfDicts[i]["usedAmount"] as! String
}
}
但是如果键对值不存在,我需要返回一个默认值(假设为“ 0”)。
答案 0 :(得分:2)
最好
struct Item {
let name:String
let amount:Double
}
let arrayOfDicts = [Item(name: "pppp", amount: 23)]
func getValue(_ name:String) -> Double {
return arrayOfDicts.first(where: { $0.name == name })?.amount ?? 0
}
答案 1 :(得分:0)
在filter(_:)
上使用 arrayOfDicts
来过滤所有带有"Name" == nameToFind
的元素,即
let arrayOfDicts = [["Name": "JW", "amount": 50], ["Name": "Red Wine", "amount": 50], ["Name": "White Wine", "amount": 50], ["Name": "X", "amount": 50], ["Name": "JW", "amount": 50], ["Name": "Y", "amount": 50], ["Name": "Y", "amount": 50]]
let nameToFind = "Smirnoff"
var amount = ""
let filteredDict = arrayOfDicts.filter {
if let name = $0["Name"] as? String {
return name == nameToFind
}
return false
}
要获取amount
,请使用
amount = "\((filteredDict.first?["amount"] as? Int) ?? 0)"