0
0
Swiftprogramming~10 mins

Lazy collections for performance in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a lazy collection from an array.

Swift
let numbers = [1, 2, 3, 4, 5]
let lazyNumbers = numbers.[1]
Drag options to blanks, or click blank then click option'
Alazy
Bmap
Cfilter
Dreduce
Attempts:
3 left
💡 Hint
Common Mistakes
Using map or filter directly creates eager collections.
2fill in blank
medium

Complete the code to lazily map numbers to their squares.

Swift
let numbers = [1, 2, 3, 4, 5]
let squares = numbers.lazy.[1] { $0 * $0 }
Drag options to blanks, or click blank then click option'
Afilter
Bmap
Creduce
DcompactMap
Attempts:
3 left
💡 Hint
Common Mistakes
Using filter instead of map.
3fill in blank
hard

Fix the error in the code to lazily filter even numbers.

Swift
let numbers = [1, 2, 3, 4, 5]
let evens = numbers.[1].filter { $0 % 2 == 0 }
Drag options to blanks, or click blank then click option'
Alazy
Bmap
Cfilter
Dreduce
Attempts:
3 left
💡 Hint
Common Mistakes
Calling filter directly without lazy causes eager evaluation.
4fill in blank
hard

Fill both blanks to lazily map numbers to strings.

Swift
let numbers = [1, 2, 3, 4, 5]
let strings = numbers.[1].[2] { "Number: \($0)" }
Drag options to blanks, or click blank then click option'
Alazy
Bmap
Cfilter
Dreduce
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping map and lazy or missing lazy.
5fill in blank
hard

Fill all three blanks to create a lazy collection that filters numbers greater than 3, maps them to strings, and then collects the results.

Swift
let numbers = [1, 2, 3, 4, 5]
let result = Array(numbers.[1].[2] { $0 > 3 }.[3] { "Value: \($0)" })
Drag options to blanks, or click blank then click option'
Alazy
Bfilter
Cmap
Dreduce
Attempts:
3 left
💡 Hint
Common Mistakes
Using reduce instead of map or missing lazy.