arraysswiftdictionaryaddition

Combine two Swift Dictionaries by sum of values


I have two Swift Dictionaries and want to combine them by adding the values for any shared key.

dict1 = ["A": 1, "B": 2, "D": 5]
dict2 = ["A": 3, "C": 9, "D": 4]

The outcome should be a new Dictionary like:

dict3 = ["A": 4, "B": 2, "C": 9, "D": 9]

Solution

  • You can use Dictionary merging method and pass the plus sign (addition operator) as the uniquingKeysWith parameter:

    let dict3 = dict1.merging(dict2, uniquingKeysWith: +)  // ["A": 4, "B": 2, "D": 9, "C": 9]