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?
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] .
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].
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With