我有两个数组,类似于下面的示例。我想做的是将两者合并在一起。如果它们的键相等,则删除重复项并将它们的值相加。
非常感谢任何帮助,非常感谢!!
当前代码:
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)
最佳答案
你就快到了!
在 uniqueKeysWith
参数中,您应该创建一个新的 Example
,其中包含相同的键以及两个参数值的总和:
let merged = Array(Dictionary([first, second].joined().map { ($0.key, $0)}, uniquingKeysWith: { Example(key: $0.key, value: $0.value + $1.value) }).values)
关于arrays - Swift - 合并两个数组,同时删除重复的键并将数组值添加在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52690464/