Peter Tretyakov Peter Tretyakov - 6 months ago 12
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
animals
' index, so
"dog"
is 1 and
"elephant"
is 2.

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

Thanks for any help!

HAS HAS
Answer

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.

Comments