Peter Tretyakov Peter Tretyakov - 5 months ago 8x
Swift Question

Return array without first element with updated index (Swift)

I have an array

let animals = ["cat", "dog", "elephant"]

And I want to return a new array without first element, but when I use

let animalsWithoutCat = animals[1...animals.count - 1]
// or
let animalsWithoutCat = animals.dropFirst()

I get an array with
' index, so
is 1 and
is 2.

I want an array with updated index (started with 0). Fewer lines of code is preferred ))

Thanks for any help!


What you want is the tail of the array.

If you implement it in an extension like this

extension Array {

  var tail: Array {
    return Array(self.dropFirst())


you can call it like this:

let animals = ["cat", "dog", "elephant"]
let animalsWithoutCat = animals.tail

If the array is empty tail is an empty array.