返回不包含第一个元素的数组,并更新索引(Swift)



我有一个数组let animals = ["cat", "dog", "elephant"]

我想返回一个没有第一个元素的新数组,但当我使用时

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

我得到一个具有animals'索引的数组,所以"dog"是1,"elephant"是2。

我想要一个索引更新的数组(以0开头)。较少的代码行是首选))

谢谢你的帮助!

您想要的是数组的tail

如果你在像这样的扩展中实现它

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

你可以这样称呼它:

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

如果数组为空,则tail为空数组。

使用:

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

或者我们将其作为扩展:

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 []
}

只需拨打:

let animalsWithoutCat = animals.arrayWithoutFirstElement()

最新更新