Weak keyword with computed properties
Is there is any sense in using
weak
keyword with computed delegate property?
Not only is it sensible to do so, but it’s important to do so. This computed property is your public interface to this private hidden property. If the computed property lacks the weak
qualifier, callers will draw incorrect conclusions about the underlying semantics.
Consider:
class SomeClass {
private weak var _delegate: SomeClassDelegate?
var delegate: SomeClassDelegate? { // whoops; this should be `weak`
get { return _delegate }
set { _delegate = newValue }
}
}
And
class CustomDelegate: SomeClassDelegate { ... }
Then
let object = SomeClass()
object.delegate = CustomDelegate()
In the absence of the the weak
qualifier on the computed property and without diving into the implementation details, the programmer might incorrectly conclude that the above is fine. But it’s not. Because the underlying _delegate
is weak
, this CustomDelegate()
instance will be deallocated immediately, and the object will end up with no delegate object. And there’s no compiler warning about this behavior.
If, however, we fix SomeClass
like so:
class SomeClass {
private weak var _delegate: SomeClassDelegate?
weak var delegate: SomeClassDelegate? { // great; matches underlying semantics
get { return _delegate }
set { _delegate = newValue }
}
}
Then the programmer will receive a very helpful warning:
let object = SomeClass()
object.delegate = CustomDelegate() // results in "Instance will be immediately deallocated because property 'delegate' is 'weak'"
They’ll then correctly deduce that they should keep their own strong reference to this CustomDelegate
for the code to work properly.
So, bottom line, you don’t technically need the weak
qualifier on the computed property that is backed by a private weak
stored property, but it’s prudent to do so to avoid mysterious bugs and/or misunderstandings about the underlying semantics.