Discover LazySequence


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


Have you ever heard of LazySequence?

When you write code that handles large sequences, this type can be very useful!

Let’s have a look at this example:

Here I’m working with a Sequence of 10 000 elements, to which I apply two transformations and then search for the first element that satisfies a predicate.

But the big issue with this code is that most of the computations performed are actually useless, because their results will never be used!

However there’s a simple way to improve this: by turning the Sequence into a LazySequence:

Thanks to this simple change, Swift will now only perform a computation when it actually needs to use its result, which dramatically reduces the number of computations that are actually executed 👌

That’s all for this article, I hope you’ve enjoyed it!

Here’s the code if you want to experiment with it:

import Foundation

(1...10_000)
    .lazy
    .map { $0 * $0 } // executed 15 times
    .filter { $0.isMultiple(of: 5) } // executed 15 times
    .first (where: { $0 > 100 })
Previous
Previous

Do you know this trick to spot memory leaks? 🤨

Next
Next

3 mistakes to avoid with Optionals