Complete the code to capture the value of 'number' inside the closure.
let number = 10 let closure = { print([1]) } closure()
The closure captures the variable 'number' from its surrounding context, so using 'number' inside the closure prints its value.
Complete the code to capture the value of 'count' as a constant inside the closure.
var count = 5 let closure = { [[1]] in print(count) } count = 10 closure()
Using '[count]' in the capture list captures the current value of 'count' as a constant inside the closure.
Fix the error in the closure to capture 'self' weakly to avoid retain cycles.
class MyClass { var value = 42 func doWork() { let closure = { [[1] self] in print(self.value) } closure() } }
Using '[weak self]' captures 'self' weakly inside the closure, preventing retain cycles.
Fill both blanks to capture 'value' strongly and 'count' weakly inside the closure.
var value = 100 var count = 20 let closure = { [[1] value, [2] count] in print(value, count ?? 0) } closure()
'value' is captured strongly by default, so just listing 'value' captures it strongly. 'count' is captured weakly using 'weak count'.
Fill all three blanks to capture 'name' unowned, 'age' weakly, and 'score' strongly inside the closure.
var name = "Alice" var age: Int? = 30 var score = 95 let closure = { [[1] name, [2] age, [3] score] in print(name, age ?? 0, score) } closure()
'name' is captured unowned, so 'unowned name'. 'age' is captured weakly, so 'weak age'. 'score' is captured strongly by default, so just 'score'.