What is the firstIndex(where:) method in Swift?
Overview
firstIndex(where:) is an array method in Swift that is used to get the first index in which an element of a collection satisfies a certain condition or predicate.
Syntax
arr.firstIndex(where: condition)
Parameters
condition: This is a closure that takes an element as an argument. It then returns a Boolean value depending on whether the element passed satisfies the condition.
Return value
The value returned is the index of the first element that satisfies the condition. If no element satisfies the condition, nil is returned.
Code example
// create arrayslet evenNumbers = [2, 4, 6, 8, 10]let twoLetterWords = ["up", "go", "me", "we"]let names = ["John", "James", "Theodore"]// get indexlet greaterThan3 = evenNumbers.firstIndex(where: {$0 > 3})!let we = twoLetterWords.firstIndex(where: {$0 == "we"})!let myName = names.firstIndex(where: {$0 == "Theodore"})!// print resultsprint(greaterThan3) // 1 = second elementprint(we) // 3 = fourth elementprint(myName) // 2 = third element
Explanation
- Lines 2-4: We create some arrays.
- Lines 7-9: We invoke
firstIndex(where:)on the arrays along with the respective conditions. - Lines 12-14: We print the results.