19

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?

Robert Atkins
  • 23,528
  • 15
  • 68
  • 97
  • 2
    Howzabout `removeAtIndex:`? Pop off the first item and you're done. Or take a slice `arr[1.. – matt Nov 18 '14 at 14:35
  • 2
    Unhelpful comment-less downvote is not helpful. @matt 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. – Robert Atkins Nov 18 '14 at 14:45
  • 1
    The docs answer those questions; you don't need to be asking me! – matt Nov 18 '14 at 14:50

2 Answers2

23

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]
MirekE
  • 11,515
  • 5
  • 35
  • 28
  • 11
    In Swift 3.0, Array has its own `dropFirst` function, so simply: `let b = a.dropFirst()` – leanne Oct 23 '16 at 15:29
18

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()

Federico Zanetello
  • 3,321
  • 1
  • 25
  • 22