Subscript

subscript(_:default:)

Accesses the value with the given key. If the dictionary doesn’t contain the given key, accesses the provided default value as if the key and default value existed in the dictionary.

Declaration

subscript(key: Dictionary<Key, Value>.Key, default defaultValue: @autoclosure () -> Dictionary<Key, Value>.Value) -> Dictionary<Key, Value>.Value { get set }

Parameters

key

The key the look up in the dictionary.

defaultValue

The default value to use if key doesn’t exist in the dictionary.

Return Value

The value associated with key in the dictionary; otherwise,defaultValue`.

Discussion

Use this subscript when you want either the value for a particular key or, when that key is not present in the dictionary, a default value. This example uses the subscript with a message to use in case an HTTP response code isn’t recognized:

var responseMessages = [200: "OK",
                        403: "Access forbidden",
                        404: "File not found",
                        500: "Internal server error"]

let httpResponseCodes = [200, 403, 301]
for code in httpResponseCodes {
    let message = responseMessages[code, default: "Unknown response"]
    print("Response \(code): \(message)")
}
// Prints "Response 200: OK"
// Prints "Response 403: Access Forbidden"
// Prints "Response 301: Unknown response"

When a dictionary’s Value type has value semantics, you can use this subscript to perform in-place operations on values in the dictionary. The following example uses this subscript while counting the occurences of each letter in a string:

let message = "Hello, Elle!"
var letterCounts: [Character: Int] = [:]
for letter in message {
    letterCounts[letter, defaultValue: 0] += 1
}
// letterCounts == ["H": 1, "e": 2, "l": 4, "o": 1, ...]

When letterCounts[letter, defaultValue: 0] += 1 is executed with a value of letter that isn’t already a key in letterCounts, the specified default value (0) is returned from the subscript, incremented, and then added to the dictionary under that key.

See Also

Accessing Keys and Values

subscript(Dictionary<Key, Value>.Key) -> Dictionary<Key, Value>.Value?

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

subscript(Dictionary<Key, Value>.Index) -> Dictionary<Key, Value>.Element

Accesses the key-value pair at the specified position.

var keys: Dictionary<Key, Value>.Keys

A collection containing just the keys of the dictionary.

var values: Dictionary<Key, Value>.Values

A collection containing just the values of the dictionary.

var first: (key: Key, value: Value)?

The first element of the collection.

func randomElement() -> (key: Key, value: Value)?

Returns a random element of the collection.

func randomElement<T>(using: inout T) -> (key: Key, value: Value)?

Returns a random element of the collection, using the given generator as a source for randomness.