The firstIndex(of:)
method is used to return the first index of a specified array element.
arr.firstIndex(of: element)
element
: The element to search for in the array or collection.
This method returns the first index where the element is found. If the element is not found, nil
is returned.
// create arrays let evenNumbers = [2, 4, 6, 8, 10] let twoLetterWords = ["up", "go", "me", "we"] let names = ["John", "James", "Theodore"] // get index of some elements let result1 = evenNumbers.firstIndex(of : 4)! let result2 = twoLetterWords.firstIndex(of: "go")! let result3 = names.firstIndex(of: "Theodore")! // print results print(result1) print(result2) print(result3)
firstIndex(of:)
method. And we store the results in some variables.RELATED TAGS
CONTRIBUTOR
View all Courses