In Swift, what's the cleanest way to get the last two items in an Array?

前端 未结 9 1207
走了就别回头了
走了就别回头了 2020-12-09 07:52

Is there a cleaner way to get the last two items of an array in Swift? In general, I try to avoid this approach since it\'s so easy to be off-by-one with the indexes. (Using

9条回答
  •  春和景丽
    2020-12-09 08:28

    I doubt it's going to make you that much happier, but the math is certainly simpler:

    func getLastTwo(array: [String]) -> [String] {
        if array.count <= 1 {
            return array
        } else {
            return array.reverse()[0...1].reverse()
        }
    }
    

    Note that reverse() is lazy, so this isn't particularly expensive.

提交回复
热议问题