Swift
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
179: Lazy Collections in Swift
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
.lazyproperty: 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." mapandfilter: These are now just the instructions on the list. They don't execute immediately.- Accessing an element (like a
forloop): 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
maporfilterlogic) 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:
- Create an array of strings called
rawLogscontaining at least 20 entries. Mix in some "INFO", "WARNING", and "CRITICAL" tags (e.g.,"INFO: System boot","CRITICAL: Disk failure"). - Use the
.lazyproperty to chain afilterthat only keeps logs containing the word "CRITICAL" and amapthat converts those logs to uppercase. - Use a
forloop or theprefix(5)method to access only the first 5 processed logs and print them to the console. - Verification: Add a
print("Processing log...")statement inside yourfilterormapclosures. Confirm that the "Processing" message only appears for the items you actually printed, not for every item in therawLogsarray.
There are no comments for now.