vfxdev vfxdev - 25 days ago 9
Swift Question

Merging dictionaries with arrays as values in Swift 4

I have the following two dictionaries I'd like to merge.

var dict1 = ["May 21": [1,2],
"May 22": [3,4]]

var dict2 = ["May 22": [5,6],
"May 23": [7,8]]


This is the result I'm looking for:

["May 21": [1, 2],
"May 22": [3, 4, 5, 6],
"May 23": [7, 8]]


I've found the new merge() functions in Swift 4:

dict1.merge(dict2, uniquingKeysWith: { (old, _) in old })


But that of course won't merge the arrays properly, just replace it with either the new or old value.

Is there a Swifty way to do this, maybe with some closures? I could of course just loop through all the keys & values like this, but this seems a bit dirty:

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
}

Answer Source

You already found the right method, you just have to concatenate the array values in the uniquing closure:

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]]