-4

I have array with 50 items. How to leave in the array only the last 30 items without for loop?

Bogdan Bogdanov
  • 882
  • 11
  • 36
  • 79
  • 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 Answers3

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 ArraySlices here.

kbunarjo
  • 1,277
  • 2
  • 11
  • 27
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
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