What is lastIndex(of:) array method in Swift?

Overview

We can use the lastIndex(of:) method to return the last index of a specified array element.

Syntax

arr.lastIndex(of: element)

Parameters

element: This is the element to search for in the array or collection.

Return value

This method returns the last index of a given element in an array. Otherwise, it returns nil.

Code example

// create arrays
let numbers = [2, 6, 5, 3, 6]
let twoLetterWords = ["up", "go", "me", "go", "up", "on"]
let names = ["John", "James", "Theodore", "Theodore"]
// get index of some elements
let result1 = numbers.lastIndex(of : 6)!
let result2 = twoLetterWords.lastIndex(of: "go")!
let result3 = names.lastIndex(of: "Theodore")!
// print results
print(result1) // 4
print(result2) // 3
print(result3) // 3

Explanation

  • Lines 2-3: We create a few arrays.
  • Lines 7-9: We get the index of the elements specified using the lastIndex(of:) method and store the results in some variables.
  • Lines 12-14: We print our results.

Free Resources