How to copy the end of the array in SWIFT?

There must be some very elegant way to use Swift to copy the end of the array from a certain index, but I couldn’t find it, so I ended this:

func getEndOfArray( 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 without additional functions?

and another…

< pre>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 people
purpose. If you need a real array, please use

< /p>

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

If the starting index is greater than (or equal to) the element count, create an empty array/slice.

There must be some very elegant way to use Swift to copy the end of the array from a certain index, but I couldn’t find it, so I ended up with this:

func getEndOfArray( 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 without additional functions?

And the other…

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

This An ArraySlice was given, which should be good enough for most people
purpose. If you need a real array, please use

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

If the starting index is greater than (or equal to) the element count, create an empty array/slice.

Leave a Comment

Your email address will not be published.