To get the index of a specified element in an array in Swift, you can use the firstIndex(of:) method.
In this example,
arr
with values 10, 20, 30, 40, 50.firstIndex(of:)
method to find the index of 30 in the array.let arr = [10, 20, 30, 40, 50]
let specifiedElement = 30
if let index = arr.firstIndex(of: specifiedElement) {
print("Index of specified element \(specifiedElement) is: \(index)")
} else {
print("Specified element not found in the array")
}
Index of specified element 30 is: 2
In this example,
arr
with values 10, 20, 30, 40, 50.firstIndex(of:)
method to find the index of 60 in the array.let arr = [10, 20, 30, 40, 50]
let specifiedElement = 60
if let index = arr.firstIndex(of: specifiedElement) {
print("Index of specified element \(specifiedElement) is: \(index)")
} else {
print("Specified element not found in the array")
}
Specified element not found in the array
In this tutorial, we learned How to get the Index of Specified Element in an Array in Swift language with well detailed examples.