Predict the output
What is the print order?
final class Node {
let name: String
init(_ name: String) { self.name = name }
deinit { print("deinit \(name)") }
}
var a: Node? = Node("A")
var b = a
a = nil
print("after a")
b = nil
print("after b")Hint 1 of 1
How many strong references exist after a = nil?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: B after a, deinit A, after b
Correct. The count drops to zero only when b is set to nil.
Why not the others?
- A deinit A, after a, after b.
bstill holds a strong reference aftera = nil. - C after a, after b, deinit A. deinit runs immediately when the last strong reference goes away.
- D after a, after b, and deinit never runs. There is no cycle, so the object is freed.