Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
swift
index
communitycreator

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

Theodore Kelechukwu Onyejiaku

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)
Getting the index of elements specified

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.

RELATED TAGS

array
swift
index
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring