Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to capture a variable in a closure.
Swift
var count = 0 let increment = { count [1] 1 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-=' will decrease the count instead of increasing it.
Using '*=' or '/=' will multiply or divide, which is not intended here.
✗ Incorrect
The closure captures the variable 'count' and increments it using '+=' operator.
2fill in blank
mediumComplete the code to create a closure that captures a constant.
Swift
let multiplier = 3 let multiply = { (value: Int) -> Int in return value [1] multiplier }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' will add instead of multiply.
Using '-' or '/' will subtract or divide, which is not the intended operation.
✗ Incorrect
The closure multiplies the input value by the captured constant 'multiplier' using the '*' operator.
3fill in blank
hardFix the error in the closure that causes a strong reference cycle.
Swift
class Counter { var count = 0 lazy var increment: () -> Void = { self.count [1] 1 } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using other operators will cause wrong arithmetic.
Not capturing 'self' weakly can cause a memory leak (not fixed in this blank).
✗ Incorrect
The closure increments 'count' using '+='. However, to avoid a strong reference cycle, 'self' should be captured weakly (not shown here).
4fill in blank
hardFill both blanks to capture self weakly and safely unwrap it inside the closure.
Swift
class Logger { var message = "Hello" lazy var log: () -> Void = { [[1] self] in guard let self = self else { return } print(self.message) } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'strong' or 'static' is incorrect for capture lists.
Using 'unowned' can cause crashes if self is nil.
✗ Incorrect
Using 'weak' captures self weakly to avoid strong reference cycles. The guard statement safely unwraps self.
5fill in blank
hardFill all three blanks to create a closure that captures self unowned and uses it safely.
Swift
class Downloader { var url = "https://example.com" lazy var download: () -> Void = { [[1] self] in print("Downloading from \(self.[2])") // Use self carefully to avoid retain cycles let task = URLSession.shared.dataTask(with: URL(string: self.url)!) { data, response, error in if let data = data { print("Downloaded \(data.count) bytes") } } task.[3]() } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'weak' instead of 'unowned' can require optional unwrapping.
Forgetting to call resume() will not start the download.
✗ Incorrect
The closure captures self as unowned to avoid retain cycles. It accesses self.url and calls task.resume() to start the download.