The lastIndex(where:)
method is an array method in Swift, which is used to get the index of the last element that satisfies a certain condition or predicate.
arr.lastIndex(where: condition)
Condition: This is a closure that takes an element as an argument. It then returns a boolean value, depending on whether the passed element satisfies the given condition.
The value returned is the index of the last element that satisfies the given condition. If no element satisfies the condition, a nil
value is returned.
// create arrayslet evenNumbers = [2, 4, 6, 8, 10]let twoLetterWords = ["us", "we", "we", "me", "he", "us"]let names = ["John", "James", "Theodore", "Peter", "Paul"]// get indexlet greaterThan3 = evenNumbers.lastIndex(where: {$0 > 3})!let lastWeIndex = twoLetterWords.lastIndex(where: {$0 == "we"})!let lastFiveLetterWord = names.lastIndex(where: {$0.count == 5})!// print resultsprint(greaterThan3) // 4 = 5th element : 10print(lastWeIndex) // 2 = third elementprint(lastFiveLetterWord) // 3 = fourth element: "Peter"
lastIndex(where:)
method on the arrays, along with their respective conditions.