Back to questions
JuniorTheoryCommon
What does the program print (lines separated by spaces)?
class Screen {
var onTap: () -> Void = {}
init() {
onTap = { [weak self] in print(self == nil) }
}
deinit { print("bye") }
}
var screen: Screen? = Screen()
let tap = screen!.onTap
screen = nil
tap()bye true
- Expecting
false: thinking the stored closure keeps the screen alive.[weak self]adds nothing to the count, soscreen = nilfrees the object anddeinitprintsbye. - Expecting a crash: mixing up
[weak self]with[unowned self]. A weakselfof a freed object isnil, and the closure runs safely.
- What changes if the closure uses
selfwithout a capture list? - Why does Swift require
self.to be written explicitly in such a closure?