<!--
{
  "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/subscript(_:)-8rfql",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Subscript",
  "symbol" : {
    "kind" : "Instance Subscript",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:SDyq_Sgxcip"
  },
  "title" : "subscript(_:)"
}
-->

# subscript(_:)

Accesses the value associated with the given key for reading and writing.

```
subscript(key: Key) -> Value? { get set }
```

## Parameters

`key`

The key to find in the dictionary.

## Return Value

The value associated with `key` if `key` is in the dictionary;
otherwise, `nil`.

## Overview

This *key-based* subscript returns the value for the given key if the key
is found in the dictionary, or `nil` if the key is not found.

The following example creates a new dictionary and prints the value of a
key found in the dictionary (`"Coral"`) and a key not found in the
dictionary (`"Cerise"`).

```
var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
print(hues["Coral"])
// Prints "Optional(16)"
print(hues["Cerise"])
// Prints "nil"
```

When you assign a value for a key and that key already exists, the
dictionary overwrites the existing value. If the dictionary doesn’t
contain the key, the key and value are added as a new key-value pair.

Here, the value for the key `"Coral"` is updated from `16` to `18` and a
new key-value pair is added for the key `"Cerise"`.

```
hues["Coral"] = 18
print(hues["Coral"])
// Prints "Optional(18)"

hues["Cerise"] = 330
print(hues["Cerise"])
// Prints "Optional(330)"
```

If you assign `nil` as the value for the given key, the dictionary
removes that key and its associated value.

In the following example, the key-value pair for the key `"Aquamarine"`
is removed from the dictionary by assigning `nil` to the key-based
subscript.

```
hues["Aquamarine"] = nil
print(hues)
// Prints "["Coral": 18, "Heliotrope": 296, "Cerise": 330]"
```

---

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)