Accesses the key-value pair at the specified position.


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



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.


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("Japan's country code is '\(countryCodes[index].key)'.")
} else {
    print("Didn't find 'Japan' as a value in the dictionary.")
// Prints "("JP", "Japan")"
// Prints "Japan's country code is 'JP'."


From Protocol

See Also

Accessing Keys and Values

subscript(Key) -> Value?

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

subscript(Key, default: () -> Value) -> Value

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.

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.