I have array with 50 items. How to leave in the array only the last 30 items without for loop?
Asked
Active
Viewed 271 times
-4
-
Possible duplicate of [In Swift, what's the cleanest way to get the last two items in an Array?](https://stackoverflow.com/questions/31007643/in-swift-whats-the-cleanest-way-to-get-the-last-two-items-in-an-array) – pckill Feb 20 '19 at 21:08
3 Answers
2
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.

kbunarjo
- 1,277
- 2
- 11
- 27
-
if I have more than 50 items can I use `array[array.count-30...]` ?? – Bogdan Bogdanov Feb 17 '19 at 01:09
-
1yes you can! You might want to have a check to make sure that your array is longer than 30 before doing the splicing though. – kbunarjo Feb 17 '19 at 01:12
0
let a1 = [1,2,3,4,5]
print(a1[2...])
so you just need the array[20...]
or array.dropfirst(20)

E.Coms
- 11,065
- 2
- 23
- 35
-
`dropFirst(_:)` is preferable, because it gracefully handles going out of bounds – Alexander Feb 17 '19 at 04:00
-
This will return 30 elements only if the array has exactly 50 elements. – Leo Dabus Feb 17 '19 at 05:07
0
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]

Leo Dabus
- 229,809
- 59
- 489
- 571