Start learning free

LESSON 115 OF 678 · ARRAYS I

Slicing an Array in Swift

Lesson

TL ; DR:

Array(arr[i..<j]) is a new array with the items from index i up to, not including, j. The original doesn't change.


let letters = ["a", "b", "c", "d", "e"]

let middle = Array(letters[1..<4])
print(middle)    // ["b", "c", "d"]

print(letters)   // ["a", "b", "c", "d", "e"]


Full lesson:

Sometimes you need only part of an array, like the first few items. A range of indexes picks that part.

1..<4 is the range from 1 up to, not including, 4. So letters[1..<4] has the items at 1, 2 and 3.

That makes the length easy to see: 4 - 1 = 3 items.

To go to the very end, end the range at the count:

let tail = Array(letters[3..<letters.count])
print(tail)   // ["d", "e"]

On its own, letters[1..<4] is an ArraySlice, a view of the array's items. Wrap it in Array(...) to copy them into a new array.

Use the copy. An ArraySlice keeps the original indexes, so letters[1..<4][0] crashes. Its first index is 1, not 0.

The original array stays as it was.


Your task

runners holds a race's runners, in the order they finished.

Put the first three in a new array named podium. Put everyone else, from index 3 to the end, in one named rest.

The code below prints both, then the length of runners.

Expected output:

Ana Ben Cleo
Dan Eve
5
STEP 1 OF 2
    Ctrl + Enter to check