<!--
{
  "availability" : [
    "iOS: 8.0.0 -",
    "iPadOS: 8.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.10.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/Dictionary/init(_:uniquingKeysWith:)",
  "metadataVersion" : "0.1.0",
  "role" : "Initializer",
  "symbol" : {
    "kind" : "Initializer",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:SD_16uniquingKeysWithSDyxq_Gqd__n_q_q__q_tqd_0_YKXEtqd_0_YKcSTRd__s5ErrorRd_0_x_q_t7ElementRtd__r0_lufc"
  },
  "title" : "init(_:uniquingKeysWith:)"
}
-->

# init(_:uniquingKeysWith:)

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.

```
init<S, E>(_ keysAndValues: S, uniquingKeysWith combine: (Value, Value) throws(E) -> Value) throws(E) where S : Sequence, E : Error, S.Element == (Key, Value)
```

## 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:

```
let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]

let firstValues = Dictionary(pairsWithDuplicateKeys,
                             uniquingKeysWith: { (first, _) in first })
// ["b": 2, "a": 1]

let lastValues = Dictionary(pairsWithDuplicateKeys,
                            uniquingKeysWith: { (_, last) in last })
// ["b": 4, "a": 3]
```

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)