Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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?

like image 909
joseph.hainline Avatar asked Jun 04 '14 05:06

joseph.hainline


People also ask

How do you check if an item is last in an array?

To get the last item without knowing beforehand how many items it contains, you can use the length property to determine it, and since the array count starts at 0, you can pick the last item by referencing the <array>. length - 1 item.

Which method of the array removes and returns the last?

pop() The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

What is endIndex in Swift?

In Swift, the endIndex property is used to get a past-the-end position. This means that the position one is greater than the last valid subscript argument. If the string is empty, it returns startIndex .


2 Answers

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.

like image 180
Era Avatar answered Oct 07 '22 01:10

Era


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 
like image 36
mythz Avatar answered Oct 07 '22 01:10

mythz