没有带有更新索引的第一个元素的返回数组(Swift)

时间:2016-05-04 19:28:39

标签: arrays swift

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

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

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

我得到一个包含animals'索引的数组,因此"dog"为1而"elephant"为2。

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

感谢您的帮助!

2 个答案:

答案 0 :(得分:9)

你想要的是数组的tail

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

extension Array {

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

}
你可以这样称呼它:

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

如果数组为空tail是一个空数组。

答案 1 :(得分:0)

使用:

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()