我有一本这样的字典:
let dic: KeyValuePairs = ["foo":2,"bar":3,"bat":5, "foo":5,"bat":7,"bar":5]
我想要具有相同键的值的和
输出应该像这样:
["foo":7, "bar":8, "bat":12]
KeyValuePairs
响应reduce
所以你可以这样做
let dic: KeyValuePairs = ["foo":2,"bar":3,"bat":5, "foo":5,"bat":7,"bar":5]
let result : [String:Int] = dic.reduce(into: [:]) { (current, new) in
current[new.key] = new.value + (current[new.key] ?? 0)
}