Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 146 ยท Collections

Lazy Sequences

Learn Swift lazy sequences - eager versus lazy evaluation, the lazy property, infinite sequences with sequence(first:next:) and stride, short-circuiting and the pitfalls of recomputation.

Most collection methods are eager: numbers.map { ... } visits every element right away and returns a complete new array. That is simple and usually exactly right. But sometimes you only need the first few results of a long pipeline, or the pipeline is conceptually infinite (all prime numbers, every line of a huge log), and doing all the work up front is wasteful or impossible.

A lazy sequence postpones the work. It remembers what you want to do and does it element by element, only when something asks for a value. This lesson shows how to switch a pipeline to lazy with .lazy, how to generate sequences from scratch with sequence(first:next:), sequence(state:next:) and stride, and where laziness helps and hurts. It builds on the protocol ideas in Collection Protocols.

Eager versus lazy: seeing the difference

The best way to understand laziness is to watch the order of events. The closures below print as they run:

Swift Eager map and filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Every element is doubled first (six lines), then every doubled value is checked (six more lines), and a whole intermediate array exists in between. Only then does the program reach the print after the pipeline. Now the same pipeline with .lazy in front:

Swift Lazy map and filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Building the pipeline prints nothing. The work starts when first asks for a value, and each element travels through the whole chain before the next one starts: double 1, check 2, double 2, check 4, double 3, check 6, double 4, check 8 (this passes) and then it stops. Elements 5 and 6 are never touched. That is called short-circuiting, and it is the main reason to use lazy sequences.

Look closely at the last two lines of the trace: doubling 4 appears a second time. Because the source is an array (a collection), the lazy filter first finds the position of the first match and then reads the element at that position, which runs the map closure for it once more. This is not a bug; it is a reminder that a lazy pipeline promises when closures may run, not how many times. We return to this under "Laziness and the cost of recomputation".

What .lazy actually returns

lazy is a property available on every Sequence. It wraps the sequence in a lazy view, and from then on map, filter, compactMap, flatMap, prefix(while:) and drop(while:) return further lazy wrappers instead of arrays:

Swift The types behind lazy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The types grow with every step (LazyFilterSequence<LazyMapSequence<Array<Int>, Int>>, as printed above), which is why you rarely write them out. You consume a lazy pipeline with a for loop, a reducing call such as first, prefix, contains or reduce, or by wrapping it in Array(...) when you want the result stored.

Lazy wrappers only keep the closure and the base sequence, so they use almost no memory regardless of the data size. When the base is a Collection, a lazy map is a collection too and can be indexed on demand:

Swift Lazy collections compute on access

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

A million labels would take noticeable time and memory as an eager array. Here, only the three strings you read are ever created.

.lazy is a decision about when closures run, never about what the result is. A lazy pipeline and the equivalent eager pipeline always agree on the final values, provided the closures have no side effects. Closures with side effects (printing, mutating variables) are exactly where the two styles can look different.

Short-circuiting methods

Lazy shines when a downstream operation can stop early. These all work with an unbounded or very long source:

Swift Stopping early

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

1... is a one-sided range: an infinite sequence of integers. It is perfectly safe as long as something stops the traversal (first, prefix, prefix(while:), a break). The eager version of the same line would loop until the integer overflowed.

Forgetting .lazy on an infinite sequence

This is the classic mistake. The code below is shown read-only because it never finishes; the sandbox would kill it after its time limit:

Swift
// Read-only example: do not run this.
let evens = (1...).map { $0 * 2 }      // eager: tries to build an infinite array
print(evens.first!)                    // never reached

Swift does not warn you. The call to map begins visiting integers and does not return, and a real program would eventually trap on arithmetic overflow or run out of memory. Put .lazy before the first transformation, or use prefix(n) before map to bound the input.

Generating sequences from nothing

Sometimes there is no collection to start from. The standard library offers three small tools that build a Sequence from a rule.

sequence(first:next:)

Give it a first value and a function that computes each next value from the previous one. The sequence ends when the function returns nil; if it never does, the sequence is infinite.

Swift sequence(first:next:)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

sequence(first:next:) turns "keep doing this to the last value" into a first-class sequence. Combined with map, prefix and reduce, it replaces many small while loops with a single expression.

sequence(state:next:)

When the next value depends on more than the previous one (Fibonacci needs two), carry hidden state. The closure receives the state as an inout parameter, updates it, and returns the next element:

Swift sequence(state:next:)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The last example shows that the state can be anything, even an iterator: here it is the array's iterator, advanced by next() each time. Whatever you choose, keep the state small and self-contained, because the sequence owns and mutates its own copy.

stride

stride(from:to:by:) and stride(from:through:by:) produce arithmetic progressions. They are lazy sequences (values are computed one at a time), they work on any Strideable type including Double, and they handle going downwards with a negative step:

Swift stride

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

to: excludes the end, through: includes it if the step lands on it. The last example shows the laziness: the range holds about nine million elements, yet prefix(3) only computes three of them.

Strides over Double work the same way, and with through: the end value is included when the step lands on it:

Swift Stride over Double

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Beware of floating-point drift with steps like 0.1: the values are computed from the start and the step, so rounding can make the last element appear or vanish. Compare floating-point results with a tolerance, or stride over integers and divide.

Laziness and the cost of recomputation

A lazy pipeline stores no results. Each time you traverse it, the closures run again. That is invisible when closures are cheap and pure, and costly otherwise:

Swift Lazy results are not cached

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each pass over squares squares all four numbers again (4, then 8, then 12 calls). The rule of thumb: use .lazy for a single traversal that may stop early, and convert to an array with Array(...) as soon as you intend to read the result more than once. Even count on a lazy filter re-runs the filter, because it cannot know the answer otherwise.

Closures with side effects

If a closure reads or changes state, laziness can change the program's behaviour, not only its timing. Imagine a closure that numbers items using a counter: in an eager pipeline the numbers follow the array order, in a lazy one they follow the consumption order, and if you traverse twice, the counter keeps going. Keep closures in lazy chains pure (the output depends only on the input and nothing outside changes).

When lazy is a good idea, and when it is not

Choose lazy when:

  • the source is infinite or enormous and you need only a prefix, a first match, or a yes/no answer;
  • you chain several transformations and then use the result once (it avoids allocating an intermediate array per step);
  • you want to defer a costly computation per element until it is really needed (thumbnails, parsed records).

Prefer eager when:

  • the collection is small. A lazy wrapper adds closure calls and generic layers, so for a handful of elements an array is usually faster;
  • you will read the result several times (see the previous section);
  • the pipeline contains a step that needs everything anyway, such as sorted(), reversed() on a sequence, or count on a filter. sorted() always produces an array, so laziness before it only delays the work;
  • you need a concrete type in an API. Lazy types are verbose and hard to store in properties; if you must return one, use some Sequence<Int> (see Opaque and Existential Types).

A compile error you will meet

A lazy pipeline is not an Array, so assigning it to an array-typed variable fails:

Swift Assigning a lazy view to an Array (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports error: cannot convert value of type 'LazyMapSequence<LazySequence<[Int]>.Elements, Int>' (aka 'LazyMapSequence<Array<Int>, Int>') to specified type '[Int]'. The fix is Array(doubled).

There is one surprising twist. If you put the annotation directly on the pipeline, the compiler picks the eager map overload that returns an array, and .lazy quietly does nothing:

Swift A type annotation can silently make it eager

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

When you rely on laziness, leave the type to inference.

A practical example: finding the first match in a stream

Lines of a log, parsed lazily, stopping at the first error:

Swift Searching a long log lazily

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Lines after the first ERROR are never parsed in the first query. The second query visits every line because counting needs all of them, so .lazy does not help there, but it also costs nothing extra: no intermediate arrays are created.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you write let r = numbers.lazy.map { $0 * 2 }?

    Building a lazy pipeline does no work. The closure runs for an element only when a consumer such as first, prefix or a for-in loop asks for it.
  2. 2. Which expression safely produces the first five squares of the positive integers?

    Without .lazy the map would try to build an infinite array and never return. With .lazy, prefix(5) stops the traversal after five squares.
  3. 3. A lazy map has a side effect (a counter). You iterate the result twice. How many times does the closure run per element?

    Lazy sequences do not cache anything. Every traversal re-evaluates the closures. Use Array(...) to materialize once.
  4. 4. What does sequence(first: 1) { $0 * 3 } produce?

    The sequence never returns nil, so it is infinite. Bound it with prefix(n) or prefix(while:) before collecting.
  5. 5. Why is stride(from: 0.0, to: 1.0, by: 0.1) risky to compare against exact values?

    Decimal fractions such as 0.1 cannot be represented exactly in binary floating point, so computed positions can differ slightly from what you wrote.

Summary

  • Eager methods compute everything at once and return an array; .lazy postpones the work until a value is requested.
  • A lazy pipeline passes each element through the whole chain, and consumers like first, prefix, contains and prefix(while:) stop early.
  • Lazy views store the closure, not the results, so every traversal recomputes. Materialize with Array(...) when you need results more than once.
  • sequence(first:next:), sequence(state:next:) and stride build sequences from rules, including infinite ones; always bound infinite sequences.
  • Keep closures in lazy chains pure, avoid lazy for small data and for steps like sorted() that need everything.
  • Forgetting .lazy before map on an infinite range never returns.

Next: Slices and Views