Swift How to Get an Index of an Item in an Array

To get the first index of an item in an array in Swift, use the array.firstIndex(where:) method.

For instance, let’s find the first occurrence of the string “a” in an array:

let arr = ["a", "b", "c", "b", "a"]
let i1 = arr.firstIndex(where: {$0 == "a"})

print(i1!)

Output:

0

Don’t let the $0 notation confuse you.

Here is how it works:

  • The firstIndex() method goes through the array of items.
  • It assigns each item to variable $0 one by one.
  • Then it checks if the condition holds for that item.
  • When it encounters the first item that matches the condition, it returns the index (as an optional).

If you are still confused about the $0 notation, feel free to check this article.

You can apply similar logic to find an index of an array of objects.

Also, as you can see, this approach only finds the first index, not all of them.

To find out all the indexes of a specific item in an array, please continue reading.

How to Find the Index of an Object in an Array of Objects

You can use the array.firstIndex(where:) method to find an object that meets a specific criterion.

This is useful when you have an array of objects with properties based on which you are searching.

For example, let’s create a class that represents a Student.

class Student {
    let name: String
    init(name: String) {
        self.name = name   
    }
}

Next, let’s create an array of students:

let student1 = Student(name: "Alice")
let student2 = Student(name: "Bob")
let student3 = Student(name: "Charlie")

let students = [student1, student2, student3]

Now, let’s use the array.firstIndex(where:) method to find the position of a student called Bob:

let bob_pos = students.firstIndex(where: {$0.name == "Bob"})

print("Bob is at position \(bob_pos!).")

Output:

Bob is at position 1.

But what if you have more than one element you want to find?

In this case, using the firsIndex() is not enough as it only returns the first index.

Instead, you have to group, filter, and map the array in a specific way.

In the next section, we are going to take a look at how.

How to Find All Indexes of a Value in an Array in Swift

So far you’ve learned how to find the first index of a specific element in an array in Swift.

But what if you want to find them all?

To find all the indexes of a value in the Swift array:

  1. Group each array element with an index.
  2. Filter the resulting array based on a criterion.
  3. Map the result to only contain the indexes.

Here is the idea in code:

arr.enumerated().filter{ $0.element == something }.map{ $0.offset }

For example, let’s find the indexes of the letter “a” in the array:

let arr = ["a", "b", "a", "b", "a"]
let idxs = arr.enumerated().filter{ $0.element == "a" }.map{ $0.offset }
print(idxs)

If you have an array of objects, you can use a similar approach.

For example, let’s find out all the Student object whose name is “Bob” in the array:

class Student {
    let name: String
    init(name: String) {
        self.name = name   
    }
}

let students = [
    Student(name: "Alice"),
    Student(name: "Bob"),
    Student(name: "Charlie"),
    Student(name: "Bob")
]

// Find indexes of student Bob:
let indexes = students.enumerated().filter{ $0.element.name == "Bob" }.map{ $0.offset }
print(indexes)

How Does It Work?

Please, have a look at this piece of code:

arr.enumerated().filter{ $0.element == something }.map{ $0.offset }

There are three things that you may be unfamiliar with:

  1. The enumerated() method.
  2. The filter() method with $0.
  3. The map() method with $0.

Let me briefly explain what these do.

  1. The enumerated() method converts an array of items to an array of (index, item) pairs. Swift calls these (offset, element) pairs.
  2. The filter() method filters out all the elements of the (offset, element) pairs where the element does not meet a criterion.
  3. The map() method converts the resulting array of (offset, element) pairs to an array of offsets.

Let’s take a step-by-step look at the process of finding all elements that equal to “a”:

1. Enumerate the array with the enumerated() method.

let idxs = arr.enumerated()

for pair in idxs {
    print(pair)
}

Output:

(offset: 0, element: "a")
(offset: 1, element: "b")
(offset: 2, element: "a")
(offset: 3, element: "b")
(offset: 4, element: "a")

2. Filter out all the pairs where the element is not “a”:

let idxs = arr.enumerated().filter{ $0.element == "a" }

for pair in idxs {
    print(pair)
}

Now we are left with pairs that only contain elements that are “a”:

(offset: 0, element: "a")
(offset: 2, element: "a")
(offset: 4, element: "a")

3. Transform pairs to an array of indexes

let idxs = arr.enumerated().filter{ $0.element == "a" }.map { $0.offset }

for pair in idxs {
    print(pair)
}

Output:

0
2
4

And there you have it!

Conclusion

Today you learned how to get the index of the first element of an array that matches a criterion.

arr.firstIndex(where: {$0 == something})

You also learned how to get all the indexes of array items that meet the criterion.

arr.enumerated().filter{ $0.element == something }.map{ $0.offset }

Thanks for reading. I hope you find it useful.

Happy coding!

Scroll to Top