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

# updateValue(_:forKey:)

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

```
@discardableResult mutating func updateValue(_ value: Value, forKey key: Key) -> Value?
```

## Parameters

`value`

The new value to add to the dictionary.

`key`

The key to associate with `value`. If `key` already exists in
the dictionary, `value` replaces the existing associated value. If
`key` isn’t already a key of the dictionary, the `(key, value)` pair
is added.

## Return Value

The value that was replaced, or `nil` if a new key-value pair
was added.

## Discussion

Use this method instead of key-based subscripting when you need to know
whether the new value supplants the value of an existing key. If the
value of an existing key is updated, `updateValue(_:forKey:)` returns
the original value.

```
var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]

if let oldValue = hues.updateValue(18, forKey: "Coral") {
    print("The old value of \(oldValue) was replaced with a new one.")
}
// Prints "The old value of 16 was replaced with a new one."
```

If the given key is not present in the dictionary, this method adds the
key-value pair and returns `nil`.

```
if let oldValue = hues.updateValue(330, forKey: "Cerise") {
    print("The old value of \(oldValue) was replaced with a new one.")
} else {
    print("No value was found in the dictionary for that key.")
}
// Prints "No value was found in the dictionary for that key."
```

---

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)