FAQ: How to combine two dictionaries in Swift?

func merging<S>(_ other: S, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows -> [Key : Value] where S : Sequence, S.Element == (Key, Value)

Creates a new dictionary instance by merging key-value pairs in a sequence. Pass a sequence of key-value pairs and a closure that takes the current and new value for duplicates keys, if no duplicates it should not be triggered.

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

let combine = a.merging(b, uniquingKeysWith: +)
// Output: ["2": "41", "1": "2", "3": "5"]


let takeNew = a.merging(b, uniquingKeysWith: { _, new in
    new
})
// Output: ["2": "1", "1": "2", "3": "5"]


let keepCurrent = a.merging(b, uniquingKeysWith: { current, _ in
    current
})
// Output: ["2": "4", "1": "2", "3": "5"]

Thanks for reading.