Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use Swift 2.0 popFirst() on an Array?

Tags:

arrays

swift2

Swift 2.0 popLast() works on an Array, like this:

var arr = [1,2,3]
let i = arr.popLast()

Now arr is [1,2] and i is 3 (wrapped in an Optional).

But although there is also a popFirst(), it doesn't compile. I'm pretty sure it used to, but it doesn't now:

var arr = [1,2,3]
let i = arr.popFirst() // compile error

What's going on here? When is this method actually usable?

like image 775
matt Avatar asked Sep 30 '15 15:09

matt


People also ask

How do you code an array in Swift?

Array Type Shorthand Syntax The type of a Swift array is written in full as Array<Element> , where Element is the type of values the array is allowed to store. You can also write the type of an array in shorthand form as [Element] .

How do you declare an array of strings in Swift?

Array in swift is written as **Array < Element > **, where Element is the type of values the array is allowed to store. The type of the emptyArray variable is inferred to be [String] from the type of the initializer. The groceryList variable is declared as “an array of string values”, written as [String].

How do arrays work in Swift?

Array's have fixed types, just like any other variable in Swift. That means that every element in an array has the same type, that cannot be changed once set. All array elements must have the same type, too. In the above examples, every item has a fixed type: String, Int and Double.

How do you create an empty array in Swift?

To create an empty string array in Swift, specify the element type String for the array and assign an empty array to the String array variable.


1 Answers

Oddly, popFirst works only on Array derivatives such as slices. So, for example, this compiles:

let arr = [1,2,3]
var arrslice = arr[arr.indices]
let i = arrslice.popFirst()

Now arrslice is [2,3] (as a slice), i is 1 (wrapped in an Optional), and arr is untouched.

So that's how to use it.

But I do not understand why this odd restriction is imposed on the use of popFirst(). I see how it is imposed (in the Swift header) but I don't see why.

EDIT Thinking about it some more, I'm guessing it has to do with efficiency. When you call popFirst() on a slice, you get what amounts to a sparse array: there is now no index 0. So we didn't have to slide all the elements down one slot; instead, we simply incremented the startIndex.

like image 95
matt Avatar answered Sep 28 '22 04:09

matt