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?

2
  • 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. Commented Aug 9, 2017 at 17:38
  • while myArray[0..<5] may be legal, array.prefix(n) is a safer way since it is bounds safe! Commented Aug 9, 2017 at 17:48

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

4
array = [1,2,3,4,5,6]
n = 5
array.prefix(n)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.