Swift - 合并两个数组,同时删除重复键并将数组值相加

Swift - Merge two arrays whilst removing keys duplicates and adding array values together

我有两个类似于下例的数组。我想做的是将两者合并在一起。如果它们的键相等,则删除重复项并将它们的两个值相加。

非常感谢任何帮助,非常感谢!!

当前代码:

struct Example: Codable {
    var key: String
    var value: Int
}

var first: [Example] = []
var second: [Example] = []

first.append(Example(key: "1", value: 10))
first.append(Example(key: "2", value: 10))
first.append(Example(key: "3", value: 10))

second.append(Example(key: "2", value: 10))
second.append(Example(key: "3", value: 10))
second.append(Example(key: "4", value: 10))


let merged = Array(Dictionary([first, second].joined().map { ([=11=].key, [=11=])}, uniquingKeysWith: {  }).values)

当前正在打印

Example(key: "3", value: 10)
Example(key: "1", value: 10)
Example(key: "2", value: 10)
Example(key: "4", value: 10)

我想做什么:

Example(key: "3", value: 20)
Example(key: "1", value: 10)
Example(key: "2", value: 20)
Example(key: "4", value: 10)

你快到了!

uniqueKeysWith 参数中,您应该创建一个包含相同键的新 Example,以及两个参数值的总和:

let merged = Array(Dictionary([first, second].joined().map { ([=10=].key, [=10=])}, uniquingKeysWith: { Example(key: [=10=].key, value: [=10=].value + .value) }).values)