Bird
Raised Fist0
Swiftprogramming~20 mins

Lazy collections for performance in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Lazy Collections Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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)")
ABefore accessing elements\nMapping 1\nFirst square: 1
BMapping 1\nBefore accessing elements\nFirst square: 1
CBefore accessing elements\nMapping 1\nMapping 2\nMapping 3\nMapping 4\nMapping 5\nFirst square: 1
DMapping 1\nMapping 2\nMapping 3\nMapping 4\nMapping 5\nBefore accessing elements\nFirst square: 1
Attempts:
2 left
💡 Hint
Remember that lazy collections delay computation until elements are accessed.
❓ Predict Output
intermediate
2: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))
A4 times
B2 times
C10 times
D5 times
Attempts:
2 left
💡 Hint
The filter stops after finding enough elements for prefix(2).
🔧 Debug
advanced
2: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
ABecause the print statement is inside a closure that is immediately executed
BBecause the lazy map closure is never executed without accessing elements
CBecause the array is empty
DBecause lazy collections do not support print statements
Attempts:
2 left
💡 Hint
Think about when lazy collections run their closures.
❓ Predict Output
advanced
2: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)")
AStart accessing\nFiltering 1\nFiltering 2\nFiltering 3\nFiltering 4\nFiltering 5\nMapping 1\nMapping 3\nMapping 5\nResult: [10, 30]
BFiltering 1\nFiltering 2\nFiltering 3\nFiltering 4\nFiltering 5\nMapping 1\nMapping 3\nMapping 5\nStart accessing\nResult: [10, 30]
CStart accessing\nFiltering 1\nMapping 1\nFiltering 2\nFiltering 3\nMapping 3\nResult: [10, 30]
DStart accessing\nFiltering 1\nMapping 1\nFiltering 2\nMapping 2\nFiltering 3\nMapping 3\nResult: [10, 20, 30]
Attempts:
2 left
💡 Hint
Remember lazy evaluation stops once prefix(2) elements are found.
🧠 Conceptual
expert
2:00remaining
Why use lazy collections for performance in Swift?
Which of the following best explains why lazy collections improve performance?
AThey automatically parallelize operations across CPU cores
BThey compute all elements immediately to avoid delays later
CThey store all intermediate results in memory for faster access
DThey delay computation until elements are needed, reducing unnecessary work
Attempts:
2 left
💡 Hint
Think about when lazy collections run their operations.

Practice

(1/5)
1. What is the main benefit of using .lazy on a Swift collection?
easy
A. It delays computation until the results are actually needed.
B. It immediately processes all elements for faster access.
C. It converts the collection into an array.
D. It sorts the collection automatically.

Solution

  1. Step 1: Understand what lazy means in Swift collections

    Lazy collections do not perform operations immediately but wait until the result is requested.
  2. Step 2: Compare options with lazy behavior

    Only It delays computation until the results are actually needed. describes delaying computation, which matches lazy collections.
  3. Final Answer:

    It delays computation until the results are actually needed. -> Option A
  4. Quick Check:

    Lazy means delay work = A [OK]
Hint: Lazy means delay work until needed, not immediate processing. [OK]
Common Mistakes:
  • Thinking lazy processes all elements immediately
  • Confusing lazy with sorting or converting to array
  • Assuming lazy improves speed by precomputing
2. Which of the following is the correct syntax to create a lazy collection from an array numbers in Swift?
easy
A. let lazyNumbers = numbers.lazy
B. let lazyNumbers = numbers.lazy()
C. let lazyNumbers = lazy(numbers)
D. let lazyNumbers = numbers.toLazy()

Solution

  1. Step 1: Recall the syntax for lazy collections in Swift

    In Swift, .lazy is a property, not a method, so no parentheses are used.
  2. Step 2: Check each option

    let lazyNumbers = numbers.lazy is correct. Adding parentheses after .lazy treats it as a method (wrong). lazy(numbers) assumes a global function (doesn't exist). numbers.toLazy() uses a nonexistent method.
  3. Final Answer:

    let lazyNumbers = numbers.lazy -> Option A
  4. Quick Check:

    Lazy is a property, no parentheses = B [OK]
Hint: Use .lazy without parentheses to create lazy collections. [OK]
Common Mistakes:
  • Adding parentheses after .lazy
  • Using a function call like lazy(numbers)
  • Assuming .toLazy() exists
3. What will be the output of this Swift code?
let numbers = [1, 2, 3, 4, 5]
let lazySquares = numbers.lazy.map { x in
    print("Calculating \(x) * \(x)")
    return x * x
}
print("Before accessing elements")
let first = lazySquares.first
print("First square: \(first!)")
medium
A. Calculating 1 * 1 Before accessing elements First square: 1
B. Calculating 1 * 1 Calculating 2 * 2 Calculating 3 * 3 Calculating 4 * 4 Calculating 5 * 5 Before accessing elements First square: 1
C. Before accessing elements Calculating 1 * 1 First square: 1
D. Before accessing elements First square: 1

Solution

  1. Step 1: Understand lazy map behavior

    The map inside lazy does not run until elements are accessed. So print inside map runs only when first element is requested.
  2. Step 2: Trace the code execution order

    "Before accessing elements" prints first. Then accessing first triggers calculation and prints "Calculating 1 * 1". Finally, it prints the first square value.
  3. Final Answer:

    Before accessing elements Calculating 1 * 1 First square: 1 -> Option C
  4. Quick Check:

    Lazy delays map until first accessed = C [OK]
Hint: Lazy map runs only when elements are accessed, not before. [OK]
Common Mistakes:
  • Assuming map runs immediately on lazy collections
  • Expecting all calculations before print statement
  • Ignoring lazy evaluation order
4. Identify the error in this Swift code using lazy collections:
let numbers = [1, 2, 3, 4, 5]
let lazyFiltered = numbers.lazy.filter { $0 % 2 == 0 }
let result = lazyFiltered.map { $0 * 2 }
print(result)
medium
A. The variable 'result' should be declared with 'var' instead of 'let'.
B. The lazy collection must be converted to an array before printing.
C. You cannot chain map after filter on lazy collections.
D. The filter closure syntax is incorrect.

Solution

  1. Step 1: Understand lazy collection chaining

    Lazy collections delay computation and produce a lazy sequence, not an array.
  2. Step 2: Check printing lazy sequences

    Printing a lazy sequence directly shows its type info, not elements. To see elements, convert to array with Array(result).
  3. Final Answer:

    The lazy collection must be converted to an array before printing. -> Option B
  4. Quick Check:

    Print lazy sequence needs Array() conversion = D [OK]
Hint: Convert lazy results to Array before printing elements. [OK]
Common Mistakes:
  • Trying to print lazy sequences directly
  • Thinking lazy filter syntax is wrong
  • Believing chaining map after filter is invalid
5. You have a large array of numbers and want to find the first number greater than 1000 after doubling each number, but only process as few elements as possible. Which Swift code using lazy collections achieves this best?
hard
A. let result = numbers.lazy.filter { $0 > 1000 }.map { $0 * 2 }.first
B. let result = numbers.map { $0 * 2 }.filter { $0 > 1000 }.first
C. let result = numbers.filter { $0 > 500 }.map { $0 * 2 }.first
D. let result = numbers.lazy.map { $0 * 2 }.first { $0 > 1000 }

Solution

  1. Step 1: Understand lazy evaluation for minimal processing

    Using .lazy delays work and processes only as many elements as needed to find the first matching.
  2. Step 2: Analyze each option for efficiency

    let result = numbers.lazy.map { $0 * 2 }.first { $0 > 1000 } uses lazy map and first with condition, so it doubles numbers one by one until it finds one > 1000, stopping early. let result = numbers.map { $0 * 2 }.filter { $0 > 1000 }.first processes entire map and filter eagerly. let result = numbers.filter { $0 > 500 }.map { $0 * 2 }.first filters before doubling but not lazy, so processes all. let result = numbers.lazy.filter { $0 > 1000 }.map { $0 * 2 }.first filters lazily but filters before doubling, which may skip needed elements.
  3. Final Answer:

    let result = numbers.lazy.map { $0 * 2 }.first { $0 > 1000 } -> Option D
  4. Quick Check:

    Lazy map + first with condition = minimal processing = A [OK]
Hint: Use lazy map then first with condition to stop early. [OK]
Common Mistakes:
  • Using eager map and filter causing full processing
  • Filtering before map may skip needed elements
  • Not using lazy causing unnecessary work
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard