Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the penultimate element in an array in Swift?

Tags:

swift

element

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.

like image 716
J Musy Avatar asked Oct 22 '25 10:10

J Musy


1 Answers

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"
}
like image 109
Leo Dabus Avatar answered Oct 25 '25 02:10

Leo Dabus