
Swift Tips: Lazy Sequences
SequenceType and CollectionType have a cool property named lazy. lazy is defined by Apple as: “A sequence containing the same elements as this sequence, but on which some operations, such as map and filter, are implemented lazily.”
This is best illustrated with an example. Let’s say we have the following code:
// Create an array containing numbers from 1 to 1,000.
var numbers = [Int]()
numbers += 1…1_000let newNumbers = numbers
.filter { $0 % 2 != 0 } // Executed 1,000 times
.map { $0 * 10 } // Executed 500 timesprint(“\(newNumbers.last)”)
If we want access to the last element of newNumbers, or any element, we have to perform every single calculation needed to build the newNumbers array. That’s 1,000 iterations for `filter` and another 500 for map. Now, more lazily:
// Create an array containing numbers from 1 to 1,000.
var numbers = [Int]()
numbers += 1…1_000let newNumbers = numbers.lazy
.filter { $0 % 2 != 0 } // Executed only 3 times
.map { $0 * 10 } // Executed only 1 timesprint(“\(newNumbers.last)”)
This time, we only complete three iterations of filter and one for map.
Because we used the lazy sequence property, we actually get back a new type (LazyMapBidirectionalCollection) rather than a simple array. It’s also important to note that lazy calculations are not cached. Every time you access an element in a lazy sequence, it will be recomputed. These can sometimes be a bit tricky to debug, so one helpful tip is to put print($0) statements inside the closures.
Join us next Monday for our final article in this series. We’ll share some advice on debugging slow build times in your Swift project.
For more insights on design and development, subscribe to BPXL Craft and follow Black Pixel on Twitter.
Black Pixel is a creative digital products agency. Learn more at blackpixel.com.

