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

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

    With Swift 5, according to your needs, you may choose one of the following patterns in order to get a new array from the last two elements of an array.


    #1. Using Array's suffix(_:)

    With Swift, objects that conform to Collection protocol have a suffix(_:) method. Array's suffix(_:) has the following declaration:

    func suffix(_ maxLength: Int) -> ArraySlice
    

    Returns a subsequence, up to the given maximum length, containing the final elements of the collection.

    Usage:

    let array = [1, 2, 3, 4]
    let arraySlice = array.suffix(2)
    let newArray = Array(arraySlice)
    print(newArray) // prints: [3, 4]
    

    #2. Using Array's subscript(_:)

    As an alternative to suffix(_:) method, you may use Array's subscript(_:) subscript:

    let array = [1, 2, 3, 4]
    let range = array.index(array.endIndex, offsetBy: -2) ..< array.endIndex
    //let range = array.index(array.endIndex, offsetBy: -2)... // also works
    let arraySlice = array[range]
    let newArray = Array(arraySlice)
    print(newArray) // prints: [3, 4]
    

提交回复
热议问题