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!
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With