Contents

subscript(_:)

Accesses the key-value pair at the specified position.

Declaration

subscript(position: Dictionary<Key, Value>.Index) -> Dictionary<Key, Value>.Element { get }

Parameters

  • position:

    The position of the key-value pair to access. position must be a valid index of the dictionary and not equal to endIndex.

Return Value

A two-element tuple with the key and value corresponding to position.

Overview

This subscript takes an index into the dictionary, instead of a key, and returns the corresponding key-value pair as a tuple. When performing collection-based operations that return an index into a dictionary, use this subscript with the resulting value.

For example, to find the key for a particular value in a dictionary, use the firstIndex(where:) method.

let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
if let index = countryCodes.firstIndex(where: { $0.value == "Japan" }) {
    print(countryCodes[index])
    print("Japan's country code is '\(countryCodes[index].key)'.")
} else {
    print("Didn't find 'Japan' as a value in the dictionary.")
}
// Prints "(key: "JP", value: "Japan")"
// Prints "Japan's country code is 'JP'."

See Also

Accessing Keys and Values