How can I combine two Dictionary instances in Swift?

I love this approach:

dicFrom.forEach { (key, value) in dicTo[key] = value }

Swift 4 and 5

With Swift 4 Apple introduces a better approach to merge two dictionaries:

let dictionary = ["a": 1, "b": 2]
let newKeyValues = ["a": 3, "b": 4]

let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }
// ["b": 2, "a": 1]

let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new }
// ["b": 4, "a": 3]

You have 2 options here (as with most functions operating on containers):

  • merge mutates an existing dictionary
  • merging returns a new dictionary

Leave a Comment