In Swift, what does conforming to Collection promise beyond Sequence, and why must an endless ID generator stay a plain Sequence?
answer
- one pass or many
- makeIterator and next()
- start and end positions
- all collections are finite
basics
~20 sSwift's Sequence only promises an iterator whose next() returns elements until nil; Collection adds nondestructive multipass access through indices, startIndex and endIndex, and every collection is finite, so an endless generator can only be a Sequence.
solid answer
~40 s`Sequence` requires one thing: `makeIterator()`, returning an `IteratorProtocol` value whose `mutating next()` yields elements and then `nil`. The standard library makes no promise that a sequence can be iterated twice. `Collection` refines it: elements can be visited repeatedly and nondestructively, each has an index, and you must provide `startIndex`, `endIndex`, a subscript and `index(after:)`, with the first three expected to be O(1). A collection's indices form a finite range. An ID generator whose `next()` never returns `nil` has no `endIndex`, so it stays a `Sequence`; callers consume it with `prefix(_:)`, `first(where:)` or a `for`-`in` with `break`, and must never call anything that walks to the end, such as `Array(ids)`, `reduce` or `count(where:)`.
code
swift · 20 lines// An ID generator that never ends: a Sequence that is its own iterator.
struct EventIDGenerator: Sequence, IteratorProtocol {
private var counter: UInt64
init(startingAt first: UInt64) { counter = first }
mutating func next() -> String? {
defer { counter += 1 }
return "evt-\(counter)" // never returns nil: the sequence is endless
}
}
let ids = EventIDGenerator(startingAt: 100)
print(Array(ids.prefix(3))) // ["evt-100", "evt-101", "evt-102"]
// The same shape without a custom type:
let pageNumbers = sequence(first: 1) { $0 + 1 }
print(Array(pageNumbers.prefix(5))) // [1, 2, 3, 4, 5]
// Calling ids.count(where:) or Array(ids) here would never return.go deeper
Recall that for-in needs a Sequence, that an iterator's next() returns nil to stop, and that Array, Set and Dictionary are collections.
Explain the required members of each protocol, why Sequence makes no repeat-iteration promise, and which methods are unsafe on an endless sequence.
Choose the weakest protocol that is honest for a custom type, document complexity departures, and catch code that iterates a generic Sequence twice.
Decide which protocol a shared library's custom containers expose, weighing the algorithms callers gain against the guarantees the team must keep.
## Two protocols, two promises Swift's standard library splits iteration into two protocols. **`Sequence`** is the minimum needed for `for`-`in` and for methods such as `map`, `filter`, `contains(_:)` and `reduce`. **`Collection`** refines `Sequence` with positions. | | `Sequence` | `Collection` | |---|---|---| | Required members | `makeIterator()` | `startIndex`, `endIndex`, a subscript, `index(after:)` | | Repeated iteration | not promised | guaranteed, nondestructive | | Finite | not required | always | | `count` | no property; only `count(where:)` | yes, O(1) for random-access collections, otherwise O(*n*) | | Examples | `stride(from:to:by:)`, `sequence(first:next:)`, a custom generator | `Array`, `Set`, `Dictionary`, `Range<Int>`, `String` | ## Sequence and IteratorProtocol An **iterator** is a value conforming to `IteratorProtocol`, whose single requirement is `mutating func next() -> Element?`. Returning `nil` ends the iteration. A sequence hands out an iterator from `makeIterator()`. When a type can be its own iterator, conforming to both `Sequence` and `IteratorProtocol` is enough, because the standard library supplies `makeIterator()` as a default implementation. The documentation is explicit about repeated access: the `Sequence` protocol makes **no requirement** about whether iteration destructively consumes the sequence. Two `for`-`in` loops over a generic `Sequence` may restart, resume, or produce something else. Code that needs a second pass must know the concrete type or require `Collection`. ## What Collection adds A collection is guaranteed to be **multipass**: any element can be read again by saving its index. To conform you provide: 1. `startIndex`, the position of the first element. 2. `endIndex`, the past-the-end position. 3. A subscript that reads the element at a valid index. 4. `index(after:)`, which advances a position. The documentation expects `startIndex`, `endIndex` and the subscript to be O(1) and asks types that cannot meet that to document the departure, because other algorithms build their complexity on it. It also states that a collection's indices form a **finite** range, and that the fact that all collections are finite is what makes operations such as `contains(_:)` safe. ## Why the ID generator is a Sequence In the scenario, every event in the day's log needs a fresh identifier from a generator that never runs dry. `next()` never returns `nil`, so there is no past-the-end position to report as `endIndex`, and the finiteness guarantee would be a lie. As a `Sequence` it is honest and still useful: - `ids.prefix(3)` takes three identifiers; `prefix` stops pulling once it has enough. - `ids.first(where:)` and `ids.contains(_:)` return as soon as they find a match (and loop forever if none exists). - `zip(todayEvents, ids)` pairs each event with an identifier and stops at the end of the finite side. - `Array(ids)`, `reduce`, `count(where:)`, `sorted()` and `reversed()` walk to the end and never return; `count(where:)` and `reversed()` carry the doc note "The sequence must be finite." You do not always need a custom type. `sequence(first:next:)` and `sequence(state:next:)` build an unfolding sequence from a closure, and `stride(from:to:by:)` returns a `StrideTo`, which is a `Sequence` but not a `Collection`: it has no `count` property and no subscript, unlike the `Range<Int>` you get from `0..<10`. ## Value-type iterators and the "consumed" question When your generator is a `struct` that is its own iterator, every `for`-`in` or `prefix(_:)` works on a copy, so in practice it restarts from the stored counter. A class-based iterator would be consumed instead. Generic code over `Sequence` must assume neither, which is exactly why algorithms that need two passes are written against `Collection`. Constraining your own generic functions to these protocols is covered in the Swift lesson on generic constraints. ## Choosing the protocol for a custom type When you write your own container or generator, pick the weakest protocol that is honest: - Values produced on demand, possibly without end, or readable only once (a generator, a stream of parsed lines): `Sequence`. - Values stored and addressable by position, finite, cheap to read again: `Collection`. You then get an iterator for free, because `Collection` defaults its `Iterator` to `IndexingIterator<Self>`, which walks from `startIndex` with `index(after:)`. - Positions that can step backward, or jump in constant time: the refinements `BidirectionalCollection` and `RandomAccessCollection`, which unlock `last`, `reversed()` without copying, and an O(1) `count`. Each refinement adds guarantees callers may depend on, so claiming one you cannot keep is worse than claiming too little.
- Could you make the endless generator a `Collection` by returning `Int.max` as `endIndex`?It would compile, but it breaks the contract: a collection is documented as finite, and generic algorithms rely on that. `Array(ids)`, `sorted()` or `reduce` would try to visit every position up to `Int.max`, and the generator would claim an end it does not have. Keep it a `Sequence` and let callers bound it with `prefix(_:)`.
- Why does `stride(from: 0, to: 10, by: 2).count` not compile while `(0..<10).count` does?`stride(from:to:by:)` returns `StrideTo<Int>`, which conforms to `Sequence` only, so it has no `count` property; the compiler can only try `count(where:)` and fails to infer it. `Range<Int>` is a `RandomAccessCollection`, which provides `count` in O(1). Wrap the stride in `Array(...)` if you need its count.
- Every Sequence can be iterated twice and will restart from the beginning
- A Collection only needs makeIterator() like any Sequence
- An infinite generator should conform to Collection so callers get count
- prefix(_:) on an endless sequence never returns because it reads everything first
- stride(from:to:by:) returns a Range, so it supports subscripting