Home > Software design >  Combine two Dictionaries
Combine two Dictionaries

Time:02-20

I'm learning Swift and can't find the solution for my problem...

I have two Dictionaries and want to combine them:

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]

CodePudding user response:

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