Converting Slices Back to Arrays
Materialize a slice into a standalone array.
Slices Are Not Arrays
An ArraySlice is a distinct type from Array. Many APIs expect a concrete Array, so you often need to convert.
let original = [1, 2, 3, 4, 5]
let slice = original[1..<4]
print(type(of: slice))Array(slice)
Wrap a slice in the Array(...) initializer to make a fresh, independent array with copied elements and zero-based indices.
let original = [10, 20, 30, 40, 50]
let slice = original[2..<5]
let array = Array(slice)
print(array)
print(type(of: array))All lessons in this course
- Creating Slices with Ranges
- ArraySlice Index Semantics
- Converting Slices Back to Arrays
- prefix, suffix, and dropFirst