Swift Tips: Lazy Sequences

Blake Merryman
Aug 28, 2017 · 2 min read

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_000
let newNumbers = numbers
.filter { $0 % 2 != 0 } // Executed 1,000 times
.map { $0 * 10 } // Executed 500 times
print(“\(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_000
let newNumbers = numbers.lazy
.filter { $0 % 2 != 0 } // Executed only 3 times
.map { $0 * 10 } // Executed only 1 times
print(“\(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.

BPXL Craft

Design and technology articles from the Black Pixel team. blackpixel.com

Blake Merryman

Written by

 Software Engineer

BPXL Craft

Design and technology articles from the Black Pixel team. blackpixel.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade