What is array.firstIndex(of:) in Swift?

Overview

The firstIndex(of:) method is used to return the first index of a specified array element.

Syntax

arr.firstIndex(of: element)

Parameters

element: The element to search for in the array or collection.

Return value

This method returns the first index where the element is found. If the element is not found, nil is returned.

Example

// create arrays
let evenNumbers = [2, 4, 6, 8, 10]
let twoLetterWords = ["up", "go", "me", "we"]
let names = ["John", "James", "Theodore"]
// get index of some elements
let result1 = evenNumbers.firstIndex(of : 4)!
let result2 = twoLetterWords.firstIndex(of: "go")!
let result3 = names.firstIndex(of: "Theodore")!
// print results
print(result1)
print(result2)
print(result3)

Explanation

  • Lines 2 and 3: We create some arrays.
  • Lines 7 to 9: We get the index of the elements specified using the firstIndex(of:) method. And we store the results in some variables.
  • Lines 12 to 14: We print our results.