Instance Method


Returns the index for the given key.


func index(forKey key: Key) -> Dictionary<Key, Value>.Index?



The key to find in the dictionary.

Return Value

The index for key and its associated value if key is in the dictionary; otherwise, nil.


If the given key is found in the dictionary, this method returns an index into the dictionary that corresponds with the key-value pair.

let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
let index = countryCodes.index(forKey: "JP")

print("Country code for \(countryCodes[index!].value): '\(countryCodes[index!].key)'.")
// Prints "Country code for Japan: 'JP'."

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.

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.