In Swift, when does adding .lazy to a map or filter chain save work, and why can its closure run more than once per element?
answer
- intermediate arrays
- early exit
- stored closure, no cache
- materialize when reused
basics
~20 sSwift's .lazy saves work when you read only part of a pipeline or make a single pass, because no intermediate arrays are built; the lazy view stores the closure, not results, so every read of an element runs it again.
solid answer
~40 sEager `map` and `filter` run immediately and allocate an array per stage. `.lazy` wraps the sequence in a `LazySequence` or `LazyCollection` whose `map` and `filter` return views such as `LazyMapSequence` that keep the base and the closure and compute elements on demand. That pays off with an early exit (`first(where:)`, `prefix(_:)`, `contains(where:)`), with endless sequences, or with one pass into a final loop or fold. The view caches nothing: the standard library documents that lazy map elements are computed each time they are read. Iterating a stored lazy view of 1,000 events twice runs the closure 2,000 times, and each `first` on a lazy `filter` rescans from the start. When the result is read more than once, materialize it once with `Array(...)` and keep the closures free of side effects.
code
swift · 36 linesstruct Event {
let name: String
let durationMs: Int
}
func demo() {
let log = (1...1_000).map {
Event(name: $0 % 10 == 0 ? "purchase" : "view", durationMs: $0)
}
var calls = 0
let enrich = { (e: Event) -> String in
calls += 1
return "\(e.name):\(e.durationMs)"
}
// Early exit: the lazy chain stops at the first match.
_ = log.lazy.map(enrich).first { $0.hasPrefix("purchase") }
print("first(where:)", calls) // 10
// The trap: a stored lazy view re-runs the closure on every read.
calls = 0
let view = log.lazy.map(enrich)
_ = view.count // base count: no calls
for _ in view {} // 1,000 calls
for _ in view {} // 1,000 more
print("reused view", calls) // 2000
// The fix when the result is reused: materialize once.
calls = 0
let enriched = Array(log.lazy.map(enrich))
for _ in enriched {}
for _ in enriched {}
print("materialized", calls) // 1000
}
demo()go deeper
Recall that map and filter build arrays immediately and that .lazy defers the work until elements are read.
Explain which types .lazy returns, why an early-exit consumer saves work, and why a lazy map's count does not call the transform.
Diagnose repeated closure calls from a stored lazy view, materialize reused results, and keep side effects out of lazy closures.
Set guidance on when lazy chains are worth their type complexity in shared code, and which APIs should return arrays instead of views.
## Eager by default In Swift, `map(_:)`, `filter(_:)`, `compactMap(_:)` and `flatMap(_:)` on a `Sequence` are **eager**: they run the closure over every element immediately and return a new `Array`. A three-stage chain over a day's event log therefore allocates three arrays and runs every closure on every element, even if the caller only wanted the first purchase. ## What .lazy actually returns The `lazy` property wraps the sequence in a `LazySequence` (or a `LazyCollection` when the base is a collection). On those types, the closure-taking methods return **views** instead of arrays: | Call on a lazy base | Returns | Work done at the call | |---|---|---| | `map(_:)` | `LazyMapSequence` / `LazyMapCollection` | none: stores base and closure | | `filter(_:)` | `LazyFilterSequence` / `LazyFilterCollection` | none | | `compactMap(_:)` | a lazy map-filter-map chain | none | | `first(where:)`, `reduce`, `for`-`in` | the answer | as much as needed | The standard library describes this as giving explicit permission to store the closure and the sequence and defer the computation. Because the closure is stored, it is an escaping closure; capture rules for that are covered in the Swift lesson on closures. ## When it saves work Laziness wins whenever the consumer does not need every element of every stage: - **Early exit.** `log.lazy.map(enrich).first { $0.hasPrefix("purchase") }` stops at the first match; in the example below `enrich` runs 10 times instead of 1,000. - **Endless inputs.** A lazy chain over an ID generator that never ends is fine as long as something like `prefix(_:)` bounds it. - **One pass into a fold.** `log.lazy.filter(isPurchase).map(\.durationMs).reduce(0, +)` visits each element once and builds no intermediate arrays. - **Free metadata.** On a lazy map over a collection, `count` comes from the base collection without calling the transform. ## The trap: no memoization A lazy view is a recipe, not a result. The documentation of `LazyMapSequence` says its elements are computed lazily, **each time they're read**, by calling the transform. Consequences seen in real code: 1. A lazy view stored in a property and iterated in two places runs the transform twice per element (2,000 calls for 1,000 events in the example). 2. Subscripting a `LazyMapCollection` at the same index twice calls the closure twice. 3. On a `LazyFilterCollection`, `startIndex`, `first` and index advancement rescan the base until the predicate matches. The type's documentation warns that these may not have the usual `Collection` complexity. Reading `first` twice on a lazy filter over 1,000 events whose first match is the 100th element ran the predicate 200 times. 4. `count` on a lazy filter must run the predicate on every element, every time. 5. A closure with side effects (logging, counting, network calls) runs when and as often as the view is read, which may be never, or many times. ## Using it well - Use `.lazy` at the start of a chain that ends in an early-exit method, a bounded `prefix(_:)` or a single fold. - If the result is read more than once, **materialize** it once with `Array(lazyChain)` and pass the array around. - Keep the closures in a lazy chain pure: no counters, no I/O. - Do not expose a long lazy type in an API. Return an `Array`, or hide the view behind an opaque `some Sequence<Event>` return type, which the Swift lesson on opaque types covers. - Measure: for short arrays the eager version is often just as fast and easier to read. - Remember that a lazy view also keeps its base alive: storing `bigLog.lazy.map(enrich)` in a long-lived property retains the whole base array for as long as the view exists. The general order in which a lazy chain processes elements, one element through all stages before the next, is a property of lazy evaluation in any language; what is specific to Swift is which methods return lazy views and that those views never cache.
- Does `count` on `log.lazy.map(enrich)` run `enrich`?No. A lazy map over a collection is itself a collection with the base's indices, so `count` is taken from the base without calling the transform. A lazy `filter`, by contrast, has to run its predicate on every element to know its count.
- Why does `log.lazy.sorted()` not stay lazy?Sorting needs every element before it can return the first one, so `sorted()` on a lazy sequence is the ordinary eager method: it reads everything and returns an `Array`. Only methods that a lazy type overrides, such as `map`, `filter`, `compactMap` and `flatMap`, return lazy views.
A lazy view is a recipe card, not a cooked dish: every time someone asks for a plate, the kitchen cooks it again from the card. If the dish will be served twice, cook it once and keep it, which is what Array(...) does.
- A lazy map computes each element once and caches it for later reads
- Adding .lazy always makes a pipeline faster
- first on a lazy filter is O(1) like first on an Array
- Side effects in a lazy map closure run as soon as the chain is built
- sorted() on a lazy sequence returns another lazy view