I only want the second to last element, not the last two as in:
let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let penultimate = streets.suffix(2)
print(penultimate) // ["Douglas", "Evarts"]
Also, I do not want to use the syntax streets[3], because the array is continuously filling up with entries.
You can simply drop the last element of your collection and return the last element of the result:
extension BidirectionalCollection {
var elementBeforeLast: Element? {
return dropLast().last
}
}
Usage:
if let elementBeforeLast = streets.elementBeforeLast {
print(elementBeforeLast) // "Douglas"
}
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