Contents

subscript(_:default:)

Accesses the value with the given key, falling back to the given default value if the key isn’t found.

Declaration

subscript(key: Key, default defaultValue: @autoclosure () -> 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.

Overview

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 occurrences of each letter in a string:

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

When letterCounts[letter, default: 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