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

前端 未结 9 1206
走了就别回头了
走了就别回头了 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:25

    myList[-2:]

    Yes, I have an enhancement request filed asking for negative index notation, and I suggest you file one too.

    However, you shouldn't make this harder on yourself than you have to. The built-in global suffix function does exactly what you're after:

    let oneArray = ["uno"]
    let twoArray = ["uno", "dos"]
    let threeArray = ["uno", "dos", "tres"]
    
    let arr1 = suffix(oneArray,2) // ["uno"]
    let arr2 = suffix(twoArray,2) // ["uno", "dos"]
    let arr3 = suffix(threeArray,2) // ["dos", "tres"]
    

    The result is a slice, but you can coerce it to an Array if you need to.

    0 讨论(0)
  • 2020-12-09 08:28

    More generic answer ...

    let a1 = [1,2,3,4,5]
    let a2 = ["1","2","3","4","5"]
    
    func getLast<T>(array: [T], count: Int) -> [T] {
      if count >= array.count {
        return array
      }
      let first = array.count - count
      return Array(array[first..<first+count])
    }
    
    getLast(a1, count: 2) // [4, 5]
    getLast(a2, count: 3) // ["3", "4", "5"]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题