我可以对字典中具有相同键的值求和吗

时间:2021-08-01 17:01:35

标签: ios swift dictionary

我有一本这样的字典:

let dic: KeyValuePairs = ["foo":2,"bar":3,"bat":5, "foo":5,"bat":7,"bar":5]

我想要具有相同键的值的总和。

输出应如下所示:

["foo":7, "bar":8, "bat":12]

1 个答案:

答案 0 :(得分:1)

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)
}