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



我有一本这样的字典:

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

相关内容

  • 没有找到相关文章

最新更新