Lazy Operations

All the sequences and methods we have looked at so far this lesson have been eager, which means they perform their operations immediately, and filter, map, and flatMap return their results in arrays. But sometimes, we may want to delay operations until they are needed.

Say you have a very large array, and you want to first use map and then perform other operations. If done eagerly, map will create a new array with the same number of elements as the original one to store its results. But if we do it lazily, map will return a LazyMapSequence, which will perform each map operation directly when asked for, without using any intermediate storage.

Infinite sequences must be handled lazily, as they obviously cannot be stored.

Lazy Sequences ...

Get Beginning Swift now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.