What is the lastIndex(where:) array method in Swift?

Overview

The lastIndex(where:) method is an array method in Swift, which is used to get the index of the last element that satisfies a certain condition or predicate.

Syntax

arr.lastIndex(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 passed element satisfies the given condition.

Return value

The value returned is the index of the last element that satisfies the given condition. If no element satisfies the condition, a nil value is returned.

Code example

// create arrays
let evenNumbers = [2, 4, 6, 8, 10]
let twoLetterWords = ["us", "we", "we", "me", "he", "us"]
let names = ["John", "James", "Theodore", "Peter", "Paul"]
// get index
let greaterThan3 = evenNumbers.lastIndex(where: {$0 > 3})!
let lastWeIndex = twoLetterWords.lastIndex(where: {$0 == "we"})!
let lastFiveLetterWord = names.lastIndex(where: {$0.count == 5})!
// print results
print(greaterThan3) // 4 = 5th element : 10
print(lastWeIndex) // 2 = third element
print(lastFiveLetterWord) // 3 = fourth element: "Peter"

Code explanation

  • Lines 2–4: We create some arrays.
  • Lines 7–9: We invoke the lastIndex(where:) method on the arrays, along with their respective conditions.
  • Lines 12–14: We print the results to the console.

Free Resources