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:
f
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>
You could use filter
func getEndOfArray( arr : [Int], fromIndex : Int? = 0) -> [Int] {
let filteredArray = arr.filter({$0 <= fromIndex})
return filteredArray
}
took the liberty of changing to [Int]
for the sake of this example.
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)
You can subscript an open ended range now. This will include elements starting at index 5.
Swift 4.2
array[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]
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.