Complete the code to declare a closure property in a class.
class MyClass { var closure: (() -> Void)? = [1] }
Closure properties are often optional and initialized to nil before assignment.
Complete the code to capture self weakly in the closure to avoid retain cycles.
class MyClass { var closure: (() -> Void)? func setup() { closure = { [[1] self] in print("Hello") } } }
Using [weak self] in the closure capture list prevents strong reference cycles by not strongly capturing self.
Fix the error in the closure that causes a retain cycle by adding the correct capture list.
class MyClass { var closure: (() -> Void)? func setup() { closure = { [1] in print(self) } } }
Adding [weak self] in the closure capture list breaks the retain cycle by capturing self weakly.
Fill in the blank to weakly capture self in the closure.
class MyClass { var closure: (() -> Void)? var value: Int = 0 func setup() { closure = { [[1] self] in guard let self = self else { return } print(self.value) } } }
Capture self weakly with [weak self] and then unwrap it with guard let self = self to use a strong reference safely inside the closure.
Fill in the blanks to create a closure that captures self unowned and calls a method safely.
class MyClass { var closure: (() -> Void)? func setup() { closure = { [[1] self] in self.[2]() } } func doWork() { print("Working") } }
Using [unowned self] captures self without increasing reference count, and calling doWork() method inside the closure works safely if self is guaranteed to exist.