---
title: "index(forKey:)"
framework: swift
role: symbol
role_heading: Instance Method
path: "swift/dictionary/index(forkey:)"
---

# index(forKey:)

Returns the index for the given key.

## Declaration

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

## Parameters

- `key`: The key to find in the dictionary.

## Return Value

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

## Discussion

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(_:)](swift/dictionary/subscript(_:)-8rfql.md)
- [subscript(_:default:)](swift/dictionary/subscript(_:default:).md)
- [subscript(_:)](swift/dictionary/subscript(_:)-4bhoo.md)
- [keys](swift/dictionary/keys-swift.property.md)
- [values](swift/dictionary/values-swift.property.md)
- [first](swift/dictionary/first.md)
- [randomElement()](swift/dictionary/randomelement().md)
- [randomElement(using:)](swift/dictionary/randomelement(using:).md)
