vfx*_*dev 3 merge dictionary swift swift4
我要合并以下两个词典。
var dict1 = ["May 21": [1,2],
"May 22": [3,4]]
var dict2 = ["May 22": [5,6],
"May 23": [7,8]]
Run Code Online (Sandbox Code Playgroud)
这是我要寻找的结果:
["May 21": [1, 2],
"May 22": [3, 4, 5, 6],
"May 23": [7, 8]]
Run Code Online (Sandbox Code Playgroud)
我在Swift 4中找到了新的merge()函数:
dict1.merge(dict2, uniquingKeysWith: { (old, _) in old })
Run Code Online (Sandbox Code Playgroud)
但这当然不能正确合并数组,只是将其替换为新值或旧值。
有没有一种快速的方式来做到这一点,也许有一些关闭?我当然可以像这样遍历所有键和值,但这似乎有点脏:
func mergeDicts(dict1: [String: [Int]], dict2: [String: [Int]]) -> [String: [Int]] {
var result = dict1
for (key, value) in dict2 {
if let resultValue = result[key] {
result[key] = resultValue + value
} else {
result[key] = value
}
}
return result
}
Run Code Online (Sandbox Code Playgroud)
您已经找到了正确的方法,只需要在唯一闭包中串联数组值:
var dict1 = ["May 21": [1,2], "May 22": [3,4]]
var dict2 = ["May 22": [5,6], "May 23": [7,8]]
dict1.merge(dict2, uniquingKeysWith: +)
print(dict1)
// ["May 22": [3, 4, 5, 6], "May 23": [7, 8], "May 21": [1, 2]]
Run Code Online (Sandbox Code Playgroud)