How do I fetch the last element of an array in Swift?

swift

Solution

Update: Swift 2.0 now includes `first:T?` and `last:T?` properties built-in.

When you need to you can make the built-in Swift API's prettier by providing your own extensions, e.g:

extension Array {
    var last: T {
        return self[self.endIndex - 1]
    }
}

This lets you now access the last element on any array with:

[1,5,7,9,22].last

Problem

I can do this: ``` var a = [1,5,7,9,22] a.count // 5 a[a.count - 1] // 22 a[a.endIndex - 1] // 22 ``` but surely there's a prettier way?

Original source