Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return array without first element with updated index (Swift)

Tags:

arrays

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!

like image 864
Peter Tretyakov Avatar asked May 04 '16 19:05

Peter Tretyakov


2 Answers

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.

like image 66
HAS Avatar answered Oct 07 '22 11:10

HAS


Use:

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

var animalsWithoutCat = animals
animalsWithoutCat.removeFirst() // Removes first element ["dog", "elephant"]

Or us it as an extention:

extension Array {
func arrayWithoutFirstElement() -> Array {
    if count != 0 { // Check if Array is empty to prevent crash
        var newArray = Array(self)
        newArray.removeFirst()
        return newArray
    }
    return []
}

Simply call:

let animalsWithoutCat = animals.arrayWithoutFirstElement()
like image 38
123FLO321 Avatar answered Oct 07 '22 11:10

123FLO321