I have array with 50 items. How to leave in the array only the last 30 items without for loop?
You can use an ArraySlice
:
let lastThirty = array[20...]
Note that lastThirty
is of type ArraySlice
, so to get it back as an array, you can do:
let lastThirtyArray = Array(lastThirty)
You can read more about ArraySlice
s here .
let a1 = [1,2,3,4,5]
print(a1[2...])
so you just need the array[20...]
or array.dropfirst(20)
What you are looking for is collections method suffix
func suffix(_ maxLength: Int) -> ArraySlice
It will return n elements up to the number of elements in your collection:
let input = Array(1...100)
let last30 = input.suffix(30) // [71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.