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 arrays
let evenNumbers = [2, 4, 6, 8, 10]
let twoLetterWords = ["up", "go", "me", "we"]
let names = ["John", "James", "Theodore"]
// get index
let greaterThan3 = evenNumbers.firstIndex(where: {$0 > 3})!
let we = twoLetterWords.firstIndex(where: {$0 == "we"})!
let myName = names.firstIndex(where: {$0 == "Theodore"})!
// print results
print(greaterThan3) // 1 = second element
print(we) // 3 = fourth element
print(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.

Free Resources