Accesses the key-value pair at the specified position.
SDK
- Xcode 8.3+
Framework
- Swift Standard Library
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 toend
.Index
Return Value
A two-element tuple with the key and value corresponding to position
.
Discussion
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 first
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 "("JP", "Japan")"
// Prints "Japan's country code is 'JP'."