Reputation: 561
The function index of an Swift array returns the first element based on the condition inside the where clause. Is there a way to get the last element with this condition?
For example, I want something like this (I know there is no function called lastIndex. This function or similar is what I'm searching for):
let array = [1, 2, 3, 4, 5, 3, 6]
let indexOfLastElementEquals3 = array.lastIndex(where: { $0 == 3 })
print(indexOfLastElementEquals3) //5 (Optional)
Upvotes: 6
Views: 4733
Reputation: 539795
lastIndex(where:)
and related methods were added in Swift 4.2,
see
In earlier Swift versions you can use index(where:)
on the reversed
view of the collection:
let array = [1, 2, 3, 4, 5, 3, 6]
if let revIndex = array.reversed().index(where: { $0 % 2 != 0 } ) {
let indexOfLastOddElement = array.index(before: revIndex.base)
print(indexOfLastOddElement) // 5
}
Or as a single expression:
let indexOfLastOddElement = array.reversed().index(where: { $0 % 2 != 0 } )
.map { array.index(before: $0.base) }
print(indexOfLastOddElement) // Optional(5)
revIndex.base
returns the position after the position of revIndex
in the underlying collection, that's why we have to “subtract” one
from the index.
For arrays this can be simplified to
let indexOfLastOddElement = revIndex.base - 1
but for collections with non-integer indices (like String
)
the above index(before:)
methods is needed.
Upvotes: 10