We can use the lastIndex(of:)
method to return the last index of a specified array element.
arr.lastIndex(of: element)
element
: This is the element to search for in the array or collection.
This method returns the last index of a given element in an array. Otherwise, it returns nil
.
// create arrayslet numbers = [2, 6, 5, 3, 6]let twoLetterWords = ["up", "go", "me", "go", "up", "on"]let names = ["John", "James", "Theodore", "Theodore"]// get index of some elementslet result1 = numbers.lastIndex(of : 6)!let result2 = twoLetterWords.lastIndex(of: "go")!let result3 = names.lastIndex(of: "Theodore")!// print resultsprint(result1) // 4print(result2) // 3print(result3) // 3
lastIndex(of:)
method and store the results in some variables.