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

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

    the last two items of an array in Swift

    EDIT: first checks that myArray.count >= 2

    let myArray2:Array? = myArray.count >= 2 ? [myArray[myArray.count-2], myArray[myArray.count-1]] : nil
    

    Here it is wrapped in a function which takes the array and either returns an array containing the last two or else returns nil if the passed array does not contain at least two items.

    func getLastTwo(myArray:[String]) -> [String]? {
            return myArray.count >= 2 ? [myArray[myArray.count-2], myArray[myArray.count-1]] : nil
        }
    

提交回复
热议问题