Creates a new dictionary from the key-value pairs in the given sequence, using a combining closure to determine the value for any duplicate keys.
SDK
- Xcode 10.2+
Framework
- Swift Standard Library
Declaration
Parameters
keysAndValues
A sequence of key-value pairs to use for the new dictionary.
combine
A closure that is called with the values for any duplicate keys that are encountered. The closure returns the desired value for the final dictionary.
Discussion
You use this initializer to create a dictionary when you have a sequence of key-value tuples that might have duplicate keys. As the dictionary is built, the initializer calls the combine
closure with the current and new values for any duplicate keys. Pass a closure as combine
that returns the value to use in the resulting dictionary: The closure can choose between the two values, combine them to produce a new value, or even throw an error.
The following example shows how to choose the first and last values for any duplicate keys: