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
- Creating Slices with Ranges
- ArraySlice Index Semantics
- Converting Slices Back to Arrays
- prefix, suffix, and dropFirst