3

I have an array of strings in Swift that I want to shorten to only the first 5. It looks like I cannot do:

myArray = myArray[0..<5]

because I get a compiler error:

Cannot subscript a value of type [String] with an index of type Countable Range

So what can I do instead?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Derry
  • 371
  • 1
  • 13
  • Show your actual code. `myArray[0..<5]` _is_ legal so you don't have what you think you have; this is probably an x-y problem, and we could get to the heart of it if you showed the real code. – matt Aug 09 '17 at 17:38
  • while `myArray[0..<5]` may be legal, `array.prefix(n)` is a safer way since it is bounds safe! – Moriarty Aug 09 '17 at 17:48

2 Answers2

8

I would say

let arr2 = arr1.prefix(5)

Keep in mind that the result is a Slice. If you want an array, coerce back to an array. So e.g.

var arr1 = // ...
arr1 = Array(arr1.prefix(5))

However, the notation arr1[0..<5] is legal, though with the same proviso: it's a slice and would need to be cast back to an array in order to assign it where an array is expected.

matt
  • 515,959
  • 87
  • 875
  • 1,141
3
array = [1,2,3,4,5,6]
n = 5
array.prefix(n)
Moriarty
  • 515
  • 3
  • 17