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.
arr.firstIndex(where: condition)
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.
The value returned is the index of the first element that satisfies the condition. If no element satisfies the condition, nil
is returned.
// 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
firstIndex(where:)
on the arrays along with the respective conditions.