Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first n elements from array of Int in Swift [duplicate]

Tags:

arrays

ios

swift

How can I remove the first n elements from an array of Int in Swift?

For example:

var array = [0, 1, 2, 3, 4, 5, 6] let n = 4 

The result array contains these elements:

[4, 5, 6] 
like image 630
Matteo Serpentoni Avatar asked Jun 08 '16 13:06

Matteo Serpentoni


People also ask

How do you remove duplicates from an array in place in Swift?

That provides two methods: one called removingDuplicates() that returns an array with duplicates removed, and one called removeDuplicates() that changes the array in place.

How do I filter an array in Swift?

To filter an array in Swift: Call the Array. filter() method on an array. Pass a filtering function as an argument to the method.

What is .first in Swift?

Swift version: 5.6. The first() method exists on all sequences, and returns the first item in a sequence that passes a test you specify.

How do you get the first element of an array in Swift?

To get the first element of an array in Swift, access first property of this Array. Array. first returns the first element of this array. If the array is empty, then this property returns nil .


1 Answers

let result = Array(array.dropFirst(n)) 

(Thanks to KPM and WolfLink for pointing out that let result = array.dropFirst(n) sets result to an ArraySlice which will not remain valid if the original array is released.)

like image 74
Kristopher Johnson Avatar answered Oct 14 '22 18:10

Kristopher Johnson