[weak self] vs [unowned self] — when to use which?
The difference
Both avoid bumping self's strong count and so break the cycle "object stores closure, closure holds object". They differ in behavior once self is dead:
[weak self]—selfinside becomesOptional; after deallocation it reads asnil. Always safe; the cost isguard let selfand a slightly more expensive read (side table).[unowned self]—selfis non-optional; access after deallocation is a deterministic trap "Attempted to read an unowned reference but object was already deallocated". Cheaper (the count is in the object, no side table), but it is a promise to the compiler: "self is definitely alive".
final class ViewModel {
var title = ""
var onChange: (() -> Void)?
func bind(label: UILabel) {
onChange = { [weak self] in
guard let self else { return } // closure may outlive self? → weak
label.text = self.title
}
}
}
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep