0Pricing
Swift Academy · Lesson

ArraySlice Index Semantics

Understand why slice indices keep original positions.

Slices Keep Original Indices

A key surprise: an ArraySlice does not reindex from zero. It keeps the same indices it had in the parent array.

let arr = [10, 20, 30, 40, 50]
let slice = arr[2..<5]
print(slice.startIndex)
print(slice.endIndex)

startIndex Is Not Always Zero

The startIndex of a slice equals the lower bound used to create it. For arr[2..<5] the start index is 2.

let arr = [1, 2, 3, 4, 5, 6]
let slice = arr[3..<6]
print("start:", slice.startIndex)
print("first value:", slice[slice.startIndex])

All lessons in this course

  1. Creating Slices with Ranges
  2. ArraySlice Index Semantics
  3. Converting Slices Back to Arrays
  4. prefix, suffix, and dropFirst
← Back to Swift Academy