Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy end of the Array in swift?

Tags:

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?

like image 216
Tero Tolonen Avatar asked Nov 27 '22 05:11

Tero Tolonen


2 Answers

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.

like image 82
Martin R Avatar answered Dec 16 '22 23:12

Martin R


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)
like image 37
joern Avatar answered Dec 17 '22 00:12

joern