How to copy end of the Array in swift?

There must be some really elegant way of copying end of the Array using Swift starting from some index, but I just could not find it, so I ended with this:

func getEndOfArray<T>( arr : [T], fromIndex : Int? = 0) -> [T] {
    var i=0;
    var newArray : [T] = [T]()
    for item in arr {
        if i >= fromIndex {
            newArray.append(item)
        }
        i = i + 1;
    }
    return newArray // returns copy of the array starting from index fromIndex
}

Is there a better way of doing this without extra function?


Solution 1:

And another one ...

let array = [1, 2, 3, 4, 5]
let fromIndex = 2
let endOfArray = array.dropFirst(fromIndex)
print(endOfArray) // [3, 4, 5]

This gives an ArraySlice which should be good enough for most purposes. If you need a real Array, use

let endOfArray = Array(array.dropFirst(fromIndex))

An empty array/slice is created if the start index is larger than (or equal to) the element count.

Solution 2:

You can use suffix:

let array = [1,2,3,4,5,6]
let lastTwo = array.suffix(2) // [5, 6]

As mentioned in the comment: This gives you an ArraySlice object which is sufficient for most cases. If you really need an Array object you have to cast it:

let lastTwoArray = Array(lastTwo)

Solution 3:

You can subscript an open ended range now. This will include elements starting at index 5.

Swift 4.2

array[5...]

Solution 4:

This is one possible solution, there are probably a few more

let array = [1, 2, 3, 4, 5]
let endOfArray = Array(array[2..<array.endIndex]) // [3, 4, 5]

Or with dynamic index and range check

let array = [1, 2, 3, 4, 5]
let index = 2
let endOfArray : [Int]
if index < array.count {
  endOfArray = Array(array[index..<array.endIndex]) // [3, 4, 5]
} else {
  endOfArray = array
}

The re-initializition of the array is needed since the range subscription of Array returns ArraySlice<Element>

Solution 5:

You could use the new method removeFirst(_:) in Swift 4

var array = [1, 2, 3, 4, 5]
array.removeFirst(2)
print(array) // [3, 4, 5]