我有两个数组,类似下面的例子。我想做的是把两者合并在一起。如果它们的键相等,则删除重复项并将两个值相加。
非常感谢您的帮助,非常感谢!!
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 { ($0.key, $0)}, uniquingKeysWith: { $1 }).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)