我正在尝试对具有唯一类型的字典求和-
let dict1: [String:Any] = ["type":"steps","value": 100]
let dict2: [String:Any] = ["type":"cal","value": 200]
let dict3: [String:Any] = ["type":"cal","value": 300]
let dict4 : [String:Any] = ["type":"steps","value": 400]
let dict5 : [String:Any] = ["type":"cal","value": 500]
我只是在寻找结果 -
sum is - [["type":"steps","value": 500],["type":"cal","value": 1000]]
我经历了https://developer.apple.com/documentation/swift/dictionary 但没有找到我需要的东西
请帮忙解决这个问题
最佳答案
你可以这样做:
let dict1: [String:Any] = ["type":"steps","value": 100]
let dict2: [String:Any] = ["type":"cal","value": 200]
let dict3: [String:Any] = ["type":"cal","value": 300]
let dict4 : [String:Any] = ["type":"steps","value": 400]
let dict5 : [String:Any] = ["type":"cal","value": 500]
let array = [dict1,dict2,dict3,dict4,dict5]
let list :[String:[[String:Any]]] = Dictionary(grouping: array, by: {$0["type"] as? String ?? ""})
let result = list.map { (key,value) -> [String:Any] in
let sum = value.reduce(0, {$0 + ($1["value"] as? Int ?? 0)})
return ["type":key , "value":sum]
}
print(result)
输出:
[["type": "cal", "value": 1000], ["type": "steps", "value": 500]]
关于ios - 使用唯一键快速合并字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50506702/