Skip to Content
Course content

179: Lazy Collections in Swift

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're running a high-end sandwich shop. You have a set of instructions for every sandwich: "Wash the lettuce, slice the tomato, toast the bread." Now, if a customer walks in and asks for just one sandwich, you wouldn't spend the next three hours prepping 500 heads of lettuce and 1,000 tomatoes "just in case" you need them later, right? That would be a massive waste of time and ingredients.

Instead, you'd wait until the order actually hits your counter. Only then do you perform those steps for that specific sandwich. That is exactly how .lazy works in Swift.

Mapping the Sandwich Shop to Swift

In a standard Swift collection, operations like map and filter are "eager." If you have an array of 1,000 items and you call .filter, Swift immediately creates a brand new array and processes all 1,000 items, even if you only plan on using the first two results. It's like prepping the entire kitchen before a single customer arrives.

When you add .lazy into the mix, the behavior shifts:

  • The .lazy property: This is your "prep list." It tells Swift, "Don't actually do any work yet; just remember the instructions I'm about to give you."
  • map and filter: These are now just the instructions on the list. They don't execute immediately.
  • Accessing an element (like a for loop): This is the "customer order." Only when you actually ask for a value does Swift go back to the list and perform the necessary operations for that one specific item.

Seeing the Performance Gap

I want to show you why this actually matters. Let's say we have a list of numbers and a very "expensive" function—something that takes a noticeable amount of time to run. If we use a standard approach, we pay the price for every single element up front.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

func expensiveOperation(_ n: Int) -> Int {
    print("Processing \(n)...") // So we can see when it happens
    return n * 2
}

// EAGER APPROACH
print("Starting eager map...")
let eagerResults = numbers.map { expensiveOperation($0) }
// All 10 numbers are processed immediately!
print("Eager map finished.")

Now, look at what happens when we use .lazy. I'll bet you can guess that the "Processing..." prints won't happen immediately.

// LAZY APPROACH
print("Starting lazy map...")
let lazyResults = numbers.lazy.map { expensiveOperation($0) }
print("Lazy map finished.") 

// Notice that nothing was printed yet! 
// The work only happens when we actually access the data.

print("Fetching the first result:")
print(lazyResults[0]) 
// ONLY NOW do we see "Processing 1..."

The "Gotcha" of Lazy Sequences

Here is something I've seen trip up a lot of developers: numbers.lazy.map(...) does not return an Array. It returns a LazyMapSequence. For most of your code, this doesn't matter because it behaves like a collection. However, if you try to pass it into a function that explicitly expects an [Int], the compiler will complain.

You can turn it back into an array by wrapping it in Array(), but be careful: doing this immediately triggers all the lazy computations. If you do Array(lazyResults), you've just turned your efficient sandwich shop back into a buffet where everything is prepped upfront, defeating the whole purpose of using .lazy in the first place.

When Should You Actually Use This?

I don't use .lazy everywhere. For small arrays, the overhead of managing the lazy sequence can actually be slower than just doing the work. Use it when:

  • You have a massive dataset and you only need a small slice of the results.
  • The transformations (the map or filter logic) are computationally expensive.
  • You are chaining multiple operations together and want to avoid creating multiple intermediate temporary arrays in memory.



📋 Practical Task

Optimizing Large-Scale Log Parsing

You are building a log analyzer for a server that generates millions of lines of text. You only need to find the first 5 "CRITICAL" error messages and format them for a report. Processing the entire log file would crash the app due to memory limits.

Your Task:

  1. Create an array of strings called rawLogs containing at least 20 entries. Mix in some "INFO", "WARNING", and "CRITICAL" tags (e.g., "INFO: System boot", "CRITICAL: Disk failure").
  2. Use the .lazy property to chain a filter that only keeps logs containing the word "CRITICAL" and a map that converts those logs to uppercase.
  3. Use a for loop or the prefix(5) method to access only the first 5 processed logs and print them to the console.
  4. Verification: Add a print("Processing log...") statement inside your filter or map closures. Confirm that the "Processing" message only appears for the items you actually printed, not for every item in the rawLogs array.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.