Swift – Index of Specific Element in Array

To find the index of a specific element in an Array in Swift, call firstIndex() method and pass the specific element for of parameter.

Array.firstIndex(of: Element) returns the index of the first match of specified element in the array. If specified element is not present in the array, then this method returns nil.

The following is a quick code snippet to find the index of the element e in Array array.

</>
Copy
if let index = array.firstIndex(of: e) {
    //index has the position of first match
} else {
    //element is not present in the array
}

Examples

In the following program, we take an array of size five, and get a random element from this array using Array.randomElement().

main.swift

</>
Copy
var names = ["apple", "banana", "cherry", "mango"]
var e = "cherry";
if let index = names.firstIndex(of: e) {
    print("Index of '\(e)' is \(index).")
} else {
    print("Element is not present in the array.")
}

Output

Index of 'cherry' is 2.
Program ended with exit code: 0

Now, let us try to find the index of an element that is not present in the array.

main.swift

</>
Copy
var names = ["apple", "banana", "cherry", "mango"]
var e = "guava";
if let index = names.firstIndex(of: e) {
    print("Index of '\(e)' is \(index).")
} else {
    print("Element is not present in the array.")
}

Output

Element is not present in the array.
Program ended with exit code: 0

Conclusion

In this Swift Tutorial, we learned how to get the index of a specific element in given Array in Swift programming.