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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.