0Pricing
Swift Academy · Lesson

Creating Slices with Ranges

Extract subsequences without copying.

Subscripting with a Range

When you subscript an array with a range, Swift does not copy elements into a new array. Instead it returns an ArraySlice that shares storage with the original array.

let numbers = [10, 20, 30, 40, 50]
let slice = numbers[1..<4]
print(slice)
print(type(of: slice))

Half-Open Range

The operator ..< creates a half-open range. 1..<4 includes indices 1, 2, and 3 but not 4.

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

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