Swift Arrays: Slices
Swift Arrays: Slices
Use ranges to create slices of arrays.
A range is a half-open interval, meaning it includes the lower bound but excludes the upper bound.
A slice is a view of an array that shares storage with the base array, meaning it is a reference to a portion of the array.
When you modify a slice, the base array is also modified.
ArraySlice
Create an ArraySlice with a range on an array.
Convert to Array if you need its own storage.
Example
let nums = [10, 20, 30, 40, 50]
let middle = nums[1...3] // ArraySlice<Int>
print(middle) // [20, 30, 40]
let copy = Array(middle) // Array<Int>
print(copy)
Use a half-open range to exclude the upper bound:
Example
let nums = [10, 20, 30, 40, 50]
let slice = nums[1..<3] // indices 1 and 2
print(slice) // [20, 30]
Slices share storage with the base array until you copy.
Tip: Slices keep original indices.
Convert to Array for zero-based indices.
One-Sided Slices
Use one-sided ranges to slice from the start or to the end.
Example
let arr = [0, 1, 2, 3, 4]
print(arr[...2]) // first three elements (0...2)
print(arr[2...]) // from index 2 to the end