Consider the following Swift code that creates a class with a closure capturing self. What will be printed when printMessage() is called?
class Printer { var message = "Hello" lazy var printClosure: () -> Void = { print(self.message) } } let printer = Printer() printer.printClosure()
Think about how closures capture self strongly by default in Swift.
The closure captures self strongly, so self.message is accessible and prints "Hello".
Choose the scenario that will cause a retain cycle leading to a memory leak.
Retain cycles happen when two objects hold strong references to each other.
If a class instance holds a strong reference to a closure that captures self strongly, they keep each other alive, causing a retain cycle.
Given the following code, what is the main cause of the memory leak?
class ViewController { var closure: (() -> Void)? func setup() { closure = { print(self) } } deinit { print("ViewController deinitialized") } } var vc: ViewController? = ViewController() vc?.setup() vc = nil
Think about how closures capture variables and how that affects object lifetime.
The closure captures self strongly, so the ViewController instance and closure keep each other alive, preventing deinitialization.
Given the code below, which option correctly fixes the retain cycle by modifying the closure?
class MyClass {
var closure: (() -> Void)?
func configure() {
closure = {
print(self)
}
}
}Consider how to capture self without creating a strong reference but still safely use it.
Using [unowned self] captures self without increasing retain count and assumes self will not be nil when closure runs.
You suspect your Swift app has a memory leak caused by retain cycles. Which step correctly describes how to detect this leak using Instruments?
Leaks instrument helps find objects that are not released properly.
The Leaks instrument detects memory that is allocated but never freed, helping identify retain cycles and leaks.