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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With