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)
To get the last element of an array in Swift, access last property of this Array. Array. last returns the last element of this array. If the array is empty, then this property returns nil .
To find the index of a specific element in an Array in Swift, call firstIndex() method and pass the specific element for of parameter. Array. firstIndex(of: Element) returns the index of the first match of specified element in the array. If specified element is not present in the array, then this method returns nil .
Returns the first element of the sequence that satisfies the given predicate.
enumerated()Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With