How do I access the not-the-first elements of an array in Swift?
Asked Answered
S

2

20

Swift's Array has a first function which returns the first element of the array (or nil if the array is empty.)

Is there a built-in function that will return the remainder of the array without the first element?

Superload answered 18/11, 2014 at 14:32 Comment(3)
Howzabout removeAtIndex:? Pop off the first item and you're done. Or take a slice arr[1..<arr.count].Venita
Unhelpful comment-less downvote is not helpful. @Venita Does removeAtIndex modify the original array? slice might be what I'm looking for, but it's a bit awkward—it's not unreasonable to expect a new language with much-touted functional features to have this built in.Superload
The docs answer those questions; you don't need to be asking me!Venita
R
24

There is one that might help you get what you are looking for:

func dropFirst<Seq : Sliceable>(s: Seq) -> Seq.SubSlice

Use like this:

let a = [1, 2, 3, 4, 5, 6, 7, 18, 9, 10]

let b = dropFirst(a) // [2, 3, 4, 5, 6, 7, 18, 9, 10]
Rheum answered 19/11, 2014 at 20:1 Comment(1)
In Swift 3.0, Array has its own dropFirst function, so simply: let b = a.dropFirst()Lederer
A
19

Correct answer for Swift 2.2, 3+:

let restOfArray = Array(array.dropFirst())

Update for Swift 3+:

as @leanne pointed out in the comments below, it looks like this is now possible:

let restOfArray = array.dropFirst()

Ataliah answered 28/6, 2016 at 15:15 Comment(2)
or: let restOfArray = originalArray.dropFirst()Lederer
It was not possible before,I'm glad that it's fixed! I'll update the answer later :)Ataliah

© 2022 - 2024 — McMap. All rights reserved.