vfxdev
vfxdev

Reputation: 708

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
}

Upvotes: 5

Views: 3831

Answers (1)

Martin R
Martin R

Reputation: 539845

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

Upvotes: 7

Related Questions