find the index of an element in an array in swift

To find the index of an element in an array in Swift, you can use the firstIndex(of:) method provided by the Array type.

Here's an example:

main.swift
let numbers = [1, 2, 3, 4, 5]
if let index = numbers.firstIndex(of: 4) {
    print("The index of 4 is \(index)")
} else {
    print("4 isn't in the array")
}
158 chars
7 lines

In this example, we have an array of numbers and we want to find the index of the element 4. We use the firstIndex(of:) method to search for the first occurrence of 4 in the array. If the method finds 4, it returns an optional value that contains the index of 4. We use optional binding (if let) to safely unwrap the value and print the index. If the method doesn't find 4, it returns nil, so we print a message indicating that 4 isn't in the array.

You can also search for an element using a closure instead of a value. Here's an example:

main.swift
let names = ["Alice", "Bob", "Charlie", "Dave", "Eve"]
if let index = names.firstIndex(where: { $0.hasPrefix("C") }) {
    print("The index of the first name starting with 'C' is \(index)")
} else {
    print("There isn't a name starting with 'C' in the array")
}
264 chars
7 lines

In this example, we have an array of names and we want to find the index of the first name that starts with the letter "C". We use the firstIndex(where:) method and provide a closure that checks whether a name has the prefix "C". The method searches the array and returns the index of the first name that matches the predicate. If the method doesn't find a matching name, it returns nil, so we print a message indicating that there isn't a name starting with "C" in the array.

related categories

gistlibby LogSnag