In Swift, why does page[0] trap when page is an ArraySlice taken from the middle of an array, and what does keeping that slice cost?
answer
- slices keep the parent's positions
- startIndex is not always zero
- a view onto shared storage
- Array(slice) for long-term storage
basics
~20 sAn ArraySlice keeps its parent array's indices, so a slice of positions 2..<5 starts at index 2 and index 0 is out of bounds. A slice also references the parent's whole buffer, so storing it long-term keeps every parent element alive.
solid answer
~40 sSlicing an array with a range, or with `prefix`, `dropFirst` and friends, returns an `ArraySlice` that is a view onto the original buffer, with no element copy. Its indices are the parent's indices: `thumbnails[2..<5]` has `startIndex == 2`, so `page[0]` traps with `Index out of bounds`. Code should use `page.startIndex`, `page.first` or `page.indices`, never literal integers. Keeping a slice is the second trap: the documentation discourages long-term storage, because a slice holds a reference to the entire parent buffer, which can look like a leak. And a slice is a different type, so passing it where `[Thumbnail]` is expected fails to compile. In both cases `Array(page)` copies just the slice's elements into a fresh array indexed from 0.
code
swift · 12 lineslet thumbnails = ["a", "b", "c", "d", "e", "f"]
let page = thumbnails[2..<5] // ArraySlice<String>: "c", "d", "e"
print(page.startIndex) // 2, not 0
print(page[page.startIndex]) // "c"
print(page.first!) // "c"
print(page[2]) // "c": the parent's index
let standalone = Array(page) // copies three elements, indices 0..<3
print(standalone[0]) // "c"
print(page[0]) // traps: Fatal error: Index out of boundsgo deeper
Recall that slicing an array gives an ArraySlice and that its first index is startIndex, not necessarily zero.
Explain that a slice is a view sharing the parent's buffer and indices, why that makes slicing O(1), and when to convert with Array(slice).
Diagnose index-out-of-bounds traps and memory retention caused by stored slices, and set review rules: index-agnostic helpers and no long-lived slices.
Decide where APIs should accept generic collections instead of concrete arrays, trading call-site convenience for avoiding hidden copies.
## What a slice is Subscripting an `Array` with a range, such as `thumbnails[2..<5]`, `thumbnails[..<3]` or `thumbnails[2...]`, returns an **`ArraySlice<Element>`**. So do the `Collection` methods that return a subsequence, such as `prefix(_:)` and `dropFirst(_:)`, and `split` returns an array of slices. The standard library describes the type as a view: instead of copying elements into new storage, a slice presents a window onto the storage of the larger array, so making one is O(1). It has the same interface as `Array`, which is exactly why its differences surprise people. ## Slices keep their parent's indices The `ArraySlice` documentation is explicit: unlike `Array` and `ContiguousArray`, the starting index of a slice isn't always zero. A slice maintains the same indices as the larger array for the same elements. | Expression | Value | |---|---| | `let page = thumbnails[2..<5]` | elements at parent positions 2, 3, 4 | | `page.startIndex` | `2` | | `page.endIndex` | `5` | | `page[2]` | the parent's third element | | `page[0]` | traps: `Fatal error: Index out of bounds` | This is a deliberate design, not an accident: an index found in a slice is valid in the parent. The documentation's example finds the first matching element in an array, searches the slice after it for the second, then reads both positions from the original array. The defensive rules are short: - Use `startIndex`, `endIndex`, `indices`, `first` and `last`, never `0` or `count - 1`, in code that might receive a slice. - Write generic helpers against `Collection` and its `Index`, so they work for arrays and slices alike; the mechanics of that are covered with generic constraints. - When a function really needs zero-based positions, convert with `Array(slice)`. ## The type mismatch `ArraySlice<Thumbnail>` is not `[Thumbnail]`. Passing a slice to a parameter typed `[Int]` fails to compile with `cannot convert value of type 'Array<Int>.SubSequence' (aka 'ArraySlice<Int>') to expected argument type '[Int]'`. The fix is either `Array(slice)` at the call site, which copies, or changing the parameter to accept `ArraySlice` or a generic collection, which does not. ## The memory cost of keeping a slice The documentation marks long-term storage of `ArraySlice` as **discouraged**: a slice holds a reference to the entire storage of the larger array, not just the part it presents, even after the original array's lifetime ends. Consider a gallery that loads 10,000 thumbnails and stores `allThumbnails.prefix(20)` in a long-lived view model as "recent". The 20-element slice keeps the entire 10,000-element buffer, and every object those elements reference, alive. In a memory graph it looks like a leak with no retain cycle. 1. Use slices freely for transient work inside a function: paging, splitting, recursive algorithms. 2. Convert with `Array(slice)` before storing in a property, a cache or a dictionary. 3. Treat a stored `ArraySlice` in a code review as a question to ask, not automatically a bug. ## Slices as cheap queues Because a slice is its own subsequence, it gains operations an `Array` lacks: `popFirst()` and `removeFirst()` are O(1) on a slice, since they only advance `startIndex`. That makes `var rest = array[...]` a cheap way to consume elements from the front, the same index-preserving behaviour viewed as a feature. ## Mutating a slice A slice is a value with copy-on-write storage, like an array. Writing `slice[3] = x` on a slice that still shares the parent's buffer copies that storage first, so the parent array is unchanged. Changes flow back only if you assign through the parent's range subscript: - On a `var` copy of the slice, `page[3] = "X"` changes that slice only. - `thumbnails[2..<5] = page` replaces those positions in the parent with the slice's elements. - `thumbnails.removeSubrange(2..<5)` changes the parent and leaves an existing slice untouched, still valid and still referencing the old buffer, because the parent copied before it mutated. So indices are shared, but values are not: index sharing is about positions, not about aliasing. ## Where this shows up in interviews The usual form is a snippet that prints `slice[0]` and asks what happens; the senior answer explains index sharing, names `startIndex`, and volunteers the retention cost and the `Array(slice)` conversion without being asked.
- A function takes `[Int]` and you have an `ArraySlice<Int>`. What are your options?Copy at the call site with `Array(slice)`, which costs O(k) for k elements, or change the function to take `ArraySlice<Int>` or a generic `Collection` of `Int`, which avoids the copy. The second is better when the function is called with slices often.
- Does mutating a slice change the parent array?No. A slice is a value with copy-on-write storage: the first mutation of a slice that shares the parent's buffer copies its elements, and the parent is unchanged. Only writing back through the parent's range subscript, `array[2..<5] = slice`, changes the parent.
A slice is like a bookmark spanning pages 40 to 60 of a book: the pages keep the book's own numbers, so there is no page 1 inside the bookmark, and holding the bookmark means keeping the whole book on the shelf.
- Assuming every ArraySlice starts at index 0
- Storing a small prefix slice of a huge array in a long-lived property
- Thinking a slice copies its elements when created
- Expecting an ArraySlice to be accepted where an Array parameter is required
- Believing mutating a slice writes through to the parent array