How to find the index of a list item in Swift?


Swift gives you some methods to perform on the collection type to get the index of a particular object.

To find the index of an item in an array in Swift, you can use the firstIndex(of:) method of the Array type. This method returns the index of the first element in the array that is equal to the given element or nil if no such element is found.

How to print the Index of List items?

Let's look at an example.

Algorithm

Step 1 − Define an input array.

Step 2 − Call the firstIndex() method on the input array.

Step 3 − Use the optional binding to get an index.

Step 4 − Print the index if found.

Example

import Foundation
let languages: [String] = ["Java", "C++", "Swift", "Python", "JavaScript"]
let targetString = "Swift"
if let index = languages.firstIndex(of: targetString) {
   print("Index of \(targetString) is \(index)")
} else {
   print("\(targetString) is not in the list")
}

Output

Index of Swift is 2

There are some other cases you should consider and learn about to get an index.

What index will return in case of duplicate objects in an array?

In this case, the firstIndex() method will return the index of the first occurrence in the list. For example,

Example

import Foundation
let languages: [String] = ["Java", "C++", "Swift", "Python", "JavaScript", "Swift"]
let targetString = "Swift"
if let index = languages.firstIndex(of: targetString) {
   print("Index of \(targetString) is \(index)")
} else {
   print("\(targetString) is not in the list")
}

Output

Index of Swift is 2

If you need to find the index of an element that meets a certain condition

You can use the index(where:) method instead. This method takes a closure that returns a Bool, and it returns the index of the first element in the array for which the closure returns true. For example,

Example

import Foundation
let languages: [String] = ["Java", "C++", "Swift", "Python", "JavaScript"]
let targetString = "Py"
if let index = languages.firstIndex(where: { $0.starts(with: targetString) }) {
   print("Index of \(targetString) is \(index)")
} else {
   print("\(targetString) is not in the list")
}

Output

Index of Py is 3

Conclusion

Swift gives us a couple of ways to get the index of an item in an array. You can use any method according to your requirements.

Updated on: 02-Jan-2023

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements