Instance Method
index(for Key:) Returns the index for the given key.
Parameters key
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
.
Discussion 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, 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.