<!--
{
  "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/merging(_:uniquingKeysWith:)-6cztu",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:SD7merging_16uniquingKeysWithSDyxq_Gqd__n_q_q__q_tqd_0_YKXEtqd_0_YKSTRd__s5ErrorRd_0_x_q_t7ElementRtd__r0_lF"
  },
  "title" : "merging(_:uniquingKeysWith:)"
}
-->

# merging(_:uniquingKeysWith:)

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 merging<S, E>(_ other: S, uniquingKeysWith combine: (Value, Value) throws(E) -> Value) throws(E) -> [Key : Value] where S : Sequence, E : Error, S.Element == (Key, Value)
```

## Parameters

`other`

A sequence of key-value pairs.

`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 are merged with the 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 newKeyValues = zip(["a", "b"], [3, 4])

let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }
// ["b": 2, "a": 1]
let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new }
// ["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)