Array.contains() / firstIndex() / lastIndex()
Methods for checking whether a specific element is contained in an array, or for searching for the index of an element.
Syntax
// Checks whether the array contains the element.
array.contains(element)
// Checks whether the array contains an element matching the condition.
array.contains(where: { condition })
// Returns the index of the first element that matches the condition.
array.firstIndex(of: element)
array.firstIndex(where: { condition })
// Returns the index of the last element that matches the condition.
array.lastIndex(of: element)
array.lastIndex(where: { condition })
Method List
| Method | Return Value | Description |
|---|---|---|
| contains(_ element:) | Bool | Returns whether the specified element is contained in the array. |
| contains(where:) | Bool | Returns whether the array contains an element satisfying the closure condition. |
| firstIndex(of:) | Int? | Returns the index of the first occurrence of the specified element. Returns nil if not found. |
| firstIndex(where:) | Int? | Returns the index of the first element satisfying the condition. |
| lastIndex(of:) | Int? | Returns the index of the last occurrence of the specified element. |
| lastIndex(where:) | Int? | Returns the index of the last element satisfying the condition. |
Sample Code
let scores = [78, 92, 55, 92, 61, 88]
// Check whether the array contains an element.
print(scores.contains(92)) // true
print(scores.contains(100)) // false
// Check whether the array contains an element matching a condition.
print(scores.contains(where: { $0 >= 90 })) // true (an element >= 90 exists)
// Search for the first matching index. The return value is optional.
if let index = scores.firstIndex(of: 92) {
print(index) // 1 (index where 92 first appears)
}
// Search for the last matching index.
if let lastIdx = scores.lastIndex(of: 92) {
print(lastIdx) // 3 (index where 92 last appears)
}
// Search for the first index satisfying a condition.
if let failIdx = scores.firstIndex(where: { $0 < 60 }) {
print(failIdx) // 2 (index where 55 first appears)
print(scores[failIdx]) // 55
}
Overview
Use contains() to check for the presence of an element; it returns a Bool. You can pass a value directly as the argument if the element conforms to Equatable. For more complex conditions, use the where: variant.
The return values of firstIndex(of:) and lastIndex(of:) are Int? (optional). Because nil is returned when no element is found, always unwrap the result safely using optional binding (if let).
For adding and removing array elements, see append() / insert() / remove(). For filtering and sorting, see filter() / sorted().
If you find any errors or copyright issues, please contact us.