Instance Methodswift 6.1.2Swift

firstIndex(of:)

Returns the first index where the specified value appears in the collection.

func firstIndex(of element: Self.Element) -> Self.Index?

Parameters

element

An element to search for in the collection.

Returns

The first index where element is found. If element is not found in the collection, returns nil.

After using firstIndex(of:) to find the position of a particular element in a collection, you can use it to access the element by subscripting. This example shows how you can modify one of the names in an array of students.

var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.firstIndex(of: "Maxime") {
    students[i] = "Max"
}
print(students)
// Prints "["Ben", "Ivy", "Jordell", "Max"]"