Challenge - 5 Problems
Swift Lazy Collections Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this lazy map operation?
Consider the following Swift code using a lazy collection. What will be printed?
Swift
let numbers = [1, 2, 3, 4, 5] let lazySquares = numbers.lazy.map { num in print("Mapping \(num)") return num * num } print("Before accessing elements") let firstSquare = lazySquares.first print("First square: \(firstSquare ?? 0)")
Attempts:
2 left
💡 Hint
Remember that lazy collections delay computation until elements are accessed.
✗ Incorrect
The lazy map does not run the closure until the element is accessed. The print before accessing elements runs first. Then only the first element is mapped and printed.
❓ Predict Output
intermediate2:00remaining
How many elements are processed in this lazy filter?
Given this Swift code, how many times will the print statement inside the filter closure run?
Swift
let numbers = Array(1...10) let lazyFiltered = numbers.lazy.filter { num in print("Filtering \(num)") return num % 2 == 0 } let firstTwo = Array(lazyFiltered.prefix(2))
Attempts:
2 left
💡 Hint
The filter stops after finding enough elements for prefix(2).
✗ Incorrect
The filter runs until it finds 2 even numbers. It checks numbers 1 to 4, printing 4 times. Then it stops.
🔧 Debug
advanced2:00remaining
Why does this lazy map not print anything?
Look at this Swift code using lazy map. Why does it produce no output?
Swift
let numbers = [1, 2, 3] let lazyMapped = numbers.lazy.map { num in print("Mapping \(num)") return num * 2 } // No further code
Attempts:
2 left
💡 Hint
Think about when lazy collections run their closures.
✗ Incorrect
Lazy collections delay running the closure until elements are accessed. Since no element is accessed, the closure never runs.
❓ Predict Output
advanced2:00remaining
What is the output of this chained lazy operation?
What will this Swift code print?
Swift
let numbers = [1, 2, 3, 4, 5] let lazyResult = numbers.lazy.filter { num in print("Filtering \(num)") return num % 2 != 0 }.map { num in print("Mapping \(num)") return num * 10 } print("Start accessing") let result = Array(lazyResult.prefix(2)) print("Result: \(result)")
Attempts:
2 left
💡 Hint
Remember lazy evaluation stops once prefix(2) elements are found.
✗ Incorrect
The filter runs until it finds 2 odd numbers (1 and 3). It filters 1, 2, 3 and maps only those odd numbers. It stops after prefix(2).
🧠 Conceptual
expert2:00remaining
Why use lazy collections for performance in Swift?
Which of the following best explains why lazy collections improve performance?
Attempts:
2 left
💡 Hint
Think about when lazy collections run their operations.
✗ Incorrect
Lazy collections delay running operations until elements are accessed, so they avoid doing work on elements that might never be used.