Instance Method

merging(_:uniquingKeysWith:)

Creates a dictionary by merging the given dictionary into this dictionary, using a combining closure to determine the value for duplicate keys.

Declaration

func merging(_ other: [Key : Value], uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows -> [Key : Value]

Parameters

other

A dictionary to merge.

combine

A closure that takes the current and new values for any duplicate keys. The closure returns the desired value for the final dictionary.

Return Value

A new dictionary with the combined keys and values of this dictionary and other.

Discussion

Use the combine closure to select a value to use in the returned dictionary, or to combine existing and new values. As the key-value pairs in other are merged with this dictionary, the combine closure is called with the current and new values for any duplicate keys that are encountered.

This example shows how to choose the current or new values for any duplicate keys:

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

let keepingCurrent = dictionary.merging(otherDictionary)
      { (current, _) in current }
// ["b": 2, "a": 1]
let replacingCurrent = dictionary.merging(otherDictionary)
      { (_, new) in new }
// ["b": 4, "a": 3]

See Also

Adding Keys and Values

func updateValue(Value, forKey: Key) -> Value?

Updates the value stored in the dictionary for the given key, or adds a new key-value pair if the key does not exist.

func merge([Key : Value], uniquingKeysWith: (Value, Value) -> Value)

Merges the given dictionary into this dictionary, using a combining closure to determine the value for any duplicate keys.

func merge<S>(S, uniquingKeysWith: (Value, Value) -> Value)

Merges the key-value pairs in the given sequence into the dictionary, using a combining closure to determine the value for any duplicate keys.

func merging<S>(S, uniquingKeysWith: (Value, Value) -> Value) -> [Key : Value]

Creates a dictionary by merging key-value pairs in a sequence into the dictionary, using a combining closure to determine the value for duplicate keys.

func reserveCapacity(Int)

Reserves enough space to store the specified number of key-value pairs.