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

Swift

Swift Problem Overview


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?

Swift Solutions


Solution 1 - Swift

As of beta5 there is now a first and last property

> In addition to Array acquiring first and last, the lazy collections also implement first (and last if they can index bidirectionally), as well as isEmpty.

Solution 2 - Swift

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

Solution 3 - Swift

You can fetch the last element of an Array by using the last property.

Code:

let lastElement = yourArray.last

Solution 4 - Swift

swift 5:

if let last = a.last {
   print(last)
}

Solution 5 - Swift

You can also get and remove last element from array
removeLast()

Example:

var array = [1, 2, 3]
let removed = array.removeLast()
// array is [1, 2]
// removed is 3

Taken from Apple docs (this source expired but you can find examples in this documentation page)

Solution 6 - Swift

edit for swift 2.2

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjoseph.hainlineView Question on Stackoverflow
Solution 1 - SwiftEraView Answer on Stackoverflow
Solution 2 - SwiftmythzView Answer on Stackoverflow
Solution 3 - SwiftBLCView Answer on Stackoverflow
Solution 4 - SwiftHamid TayebiView Answer on Stackoverflow
Solution 5 - SwiftpbaranskiView Answer on Stackoverflow
Solution 6 - SwiftAhmed SafadiView Answer on Stackoverflow