In Swift, why does subscripting an ArraySlice with the counter from enumerated() pick the wrong element or trap, and what should you use instead?
answer
- counter, not position
- slices keep parent indices
- pair indices with elements
- shorter input wins
basics
~20 senumerated() yields an Int counter starting at 0, not an index; an ArraySlice keeps its parent array's indices, so the counter points at the wrong element or past the bounds. Pair real indices with zip(slice.indices, slice).
solid answer
~40 s`enumerated()` returns an `EnumeratedSequence` of `(offset, element)` pairs, where `offset` counts from 0. The standard library documents that these counters work as indices only for zero-based, integer-indexed collections such as `Array` and `ContiguousArray`. An `ArraySlice` such as `dayLog[3...]` keeps the parent's indices `3..<7`, so `afternoon[offset]` with offset 0 traps with `Index out of bounds`, and with offset 3 silently reads the slice's first element instead of its fourth. For `String`, `Set` or `Dictionary` the counter is not even the right index type. The documented fix is `zip(slice.indices, slice)`, which pairs each element with its own index; `zip` stops at the shorter input. Since Swift 6.2, `EnumeratedSequence` is also a `Collection`, but its offsets are still counters.
code
swift · 12 lineslet dayLog = ["login", "view", "view", "purchase", "logout", "login", "purchase"]
let afternoon = dayLog[3...] // ArraySlice, indices 3..<7
for (offset, name) in afternoon.enumerated() {
// offset is 0, 1, 2, 3 -- a counter, not an index into afternoon
print(offset, name, afternoon.indices.contains(offset))
}
// Correct: pair each element with its real index
for (index, name) in zip(afternoon.indices, afternoon) where name == "purchase" {
print("purchase at index", index, dayLog[index])
}go deeper
Recall that enumerated() gives a counter starting at 0 and that it equals the index only for a plain Array.
Explain why slices keep their parent's indices and how zip(c.indices, c) pairs elements with valid positions, stopping at the shorter input.
Diagnose an index-out-of-bounds trap or a silently wrong element after a slice, and write loops that stay correct for any collection type.
Encourage index-agnostic iteration in shared helpers so code stays correct when callers pass slices, strings or custom collections, and track OS availability for 6.2 conformances.
## Offsets and indices are different things An **index** in Swift is a position in a specific collection, of that collection's `Index` type: an `Int` for `Array`, a `String.Index` for `String`, an opaque type for `Set` and `Dictionary`. An **offset** is a distance from the start, always an `Int`. For an `Array` the two coincide, because its indices start at 0. For almost everything else they do not. `enumerated()` is defined on every `Sequence` and returns an `EnumeratedSequence`, a sequence of `(offset: Int, element: Element)` pairs whose offsets are consecutive integers **starting at zero**. Its doc comment states that these counters can be used as indices only in zero-based, integer-indexed collections such as `Array` and `ContiguousArray`; for other collections they may be out of range or of the wrong type, and it recommends `zip(_:_:)` for iterating elements with their indices. ## Why the slice goes wrong An `ArraySlice` is a view into an array that **keeps the parent's indices** (why it does so is covered with arrays and slices). In the analytics scenario, the afternoon part of a day's log is `let afternoon = dayLog[3...]`, whose indices run from 3 to 6. | Loop variable | Values for `afternoon` | Valid for `afternoon[...]`? | |---|---|---| | `offset` from `enumerated()` | 0, 1, 2, 3 | only 3, and it points at the wrong element | | `afternoon.indices` | 3, 4, 5, 6 | yes | Two failure modes follow: 1. **Trap.** Reading `afternoon[0]` is out of bounds, and the program stops with `Fatal error: Index out of bounds`. 2. **Silent wrong answer.** Offset 3 happens to be a valid index, but it is the slice's *first* element, not its fourth, so code that records "purchase at offset 3" and later reads `dayLog[3]` reports the wrong event without any error. For a `String` the code does not even compile, because a `String` is subscripted with `String.Index`, not `Int`. For a `Set`, the same applies with `Set<Element>.Index`. ## The fixes - **Pair real indices with elements:** `for (index, name) in zip(afternoon.indices, afternoon)`. This is the pattern the documentation recommends, and it works for any collection. - **Iterate indices only:** `for index in afternoon.indices` when you need the position and can subscript for the element. - **Search directly:** `afternoon.firstIndex(where: { $0 == "purchase" })` returns a real index. - **Use offsets as offsets:** when you want "the third event of the afternoon" for display, `enumerated()` is exactly right; just do not subscript with it. ## How zip behaves `zip(_:_:)` returns a `Zip2Sequence` of pairs whose *i*th element combines the *i*th elements of both inputs. When the inputs differ in length, the documentation says the result is as long as the **shorter** one; extra elements are ignored, and nothing traps. That makes `zip(dayLog, 1...)` a convenient way to number events from 1, even though `1...` never ends. ## Swift 6.2: EnumeratedSequence as a Collection SE-0459, implemented in **Swift 6.2**, made `EnumeratedSequence` conform to `Collection` when its base is a collection, and to `BidirectionalCollection` and `RandomAccessCollection` under stricter conditions. Over an `Array`, for example, that brings `count`, `last` and index-based access without first copying the pairs into an array. Two things do not change: - The `offset` in each pair is still a counter from zero, not the base's index. - The conformance is gated on the standard library version. Built for an older Apple OS, the Swift 6.4 compiler warns, for example, that the conformance "is only available in macOS 26.0 or newer; this is an error in the Swift 6 language mode". ## A review checklist for index arithmetic When a loop mixes counters and positions, a few questions catch most bugs: 1. Where does the collection come from? A parameter typed `ArraySlice` or a generic `Collection` may not start at 0, and a `Substring` is not indexed by `Int` at all. 2. Is the counter used only for display or numbering? Then `enumerated()` is fine. 3. Is anything subscripted with the counter? Replace it with `indices`, `zip(c.indices, c)` or `firstIndex(where:)`. 4. Are two sequences walked together? `zip` silently truncates to the shorter one, so check that losing the tail is intended.
- When is using `enumerated()` offsets as indices actually safe?When the collection is zero-based and integer-indexed and you have not sliced it: `Array` and `ContiguousArray`, as the documentation names. Even then, `zip(array.indices, array)` or `indices` states the intent and keeps working if someone later passes a slice.
- What does `zip(events, ids)` produce when `ids` never ends?It produces exactly `events.count` pairs. `zip` stops as soon as either input runs out, so an endless ID generator can be zipped with a finite log safely; only the finite side bounds the loop.
- enumerated() returns each element's index in the collection
- An ArraySlice is always indexed from zero like a new Array
- zip traps when its two inputs have different lengths
- Since Swift 6.2 enumerated() offsets match the base collection's indices
- Offsets from enumerated() can subscript a String
Assumes Swift 6.4; EnumeratedSequence became a Collection in Swift 6.2 (SE-0459), and on Apple platforms that conformance needs an OS with the 6.2 standard library.