How to add two Dictionaries together in Swift

January 26, 2019

In a lot of objects, it's easy to add them together, think arrays, integers, and strings. However, when you try to add two dictionaries together you will get an error. This is because we need to handle the situation where keys are overlapping. Luckly, Swift has a feature called merge in order to merge dictionaries.

Let's have a look :

let dictA = ["x" : 1, "y": 2, "z": 3]
let dictB = ["x" : 99, "y": 88, "w": 0]

let combinedDict = dictA.merging(dictB) { $1 } // $1 = take dictB, $0 = take dictA

print(combinedDict) // ["x": 99, "y": 88, "z": 3, "w": 0]