Swift: Find the index of a specific element in an array

Updated: April 18, 2023 By: Khue Post a comment

Overview

Swift provides several built-in array methods that can help you find the index of an element (when knowing its value or some of its characteristics) in a given array:

  • firstIndex(of:): You can use this method to find the index of the first occurrence of a specific element in an array. It returns an optional value, so you need to unwrap it safely.
  • firstIndex(where:): This one finds the index of the first element that satisfies a given condition. It takes a closure as an argument and returns an optional value.
  • lastIndex(of:): This method can help you find the index of the last occurrence of a specific element in an array. It works similarly to the firstIndex(of:) method, but it searches from the end of the array.
  • lastIndex(where:): This dude can find the index of the last element that satisfies a given condition. It works similarly to the firstIndex(where:) method, but it searches from the end of the array.

By flexibly using one of these four methods, you can find the index of an element whether in a simple array or a deeply nested array (like an array of dictionaries). Enough theory; let’s see some practical code examples.

Examples

Using firstIndex(of:)

This example finds the index of orange in an array of fruits:

let fruits = ["apple", "banana", "orange", "mango"]
if let index = fruits.firstIndex(of: "orange") {
    print("The index of 'orange' is \(index)")
} else {
    print("Orange is not in the array")
}

Output:

The index of 'orange' is 2

Using firstIndex(where:)

This example demonstrates how to find the first index where an element satisfies a condition:

let numbers = [1, 2, 3, 4, 5]
if let index = numbers.firstIndex(where: { $0 > 3 }) {
    print("The first index where the element is greater than 3 is \(index)")
} else {
    print("No element is greater than 3")
}

Output:

The first index where the element is greater than 3 is 3

Using lastIndex(of:)

The code below does one job: find the last index of a in an array that contains some letters:

let letters = ["a", "b", "c", "a", "d"]
if let index = letters.lastIndex(of: "a") {
    print("The last index of 'a' is \(index)")
} else {
    print("a is not in the array")
}

Output:

The last index of 'a' is 3

Using lastIndex(where:)

Let’s say we have an array that stores the scores of some players (who play an unknown game). What we need to do is to find the last index where the score is less than 70:

let scores = [80, 90, 70, 60, 50]
if let index = scores.lastIndex(where: { $0 < 70 }) {
    print("The last index where the score is less than 70 is \(index)")
} else {
    print("No score is less than 70")
}

Output:

The last index where the score is less than 70 is 4

Dealing with deeply nested arrays

In the following example, we will work with an array whose elements are dictionaries. The job is to find the index of the first dictionary that contains a specific key and value pair. We will use the firstIndex(where:) method in this case:

let books = [
    ["title": "The Catcher in the Rye", "author": "J.D. Salinger"],
    ["title": "Nineteen Eighty-Four", "author": "George Orwell"],
    ["title": "Animal Farm", "author": "George Orwell"],
    ["title": "The Hitchhiker's Guide to the Galaxy", "author": "Douglas Adams"],
]
if let index = books.firstIndex(where: { $0["author"] == "George Orwell" }) {
    print("The first book by George Orwell is at index \(index)")
} else {
    print("No book by George Orwell is found")
}

Output:

The first book by George Orwell is at index 1