Good question. I agree that [guard self]
will not be applicable to all [weak self]
closures that return Void
. Folks will need to reason through the implications of "this closure will not run if self
no longer exists".
I think it's worth considering what overall portion of weak self
closures fall into the category of "it is clearly correct for the closure to not run if self
no longer exists".
I took a brief survey of [weak self]
closures in the Airbnb codebase (2M+ lines of Swift code):
- ~9,500 uses of
weak self
- ~2,000
weak self
closures that start withguard let self = self else { return }
(30%) - ~4,500
weak self
closures that useself?.
in the first line (which, forVoid
closures, implicitly does not handle the case whereself
isnil
) (47%)
These two cases (that I could trivially regex for) cover 70% of all weak self
closures in our codebase. It seems likely that this could cover an even larger percentage with more sophisticated regexes (that handle multi-line guard cases, for example.)
Within the context of a UI codebase, it seems reasonable to make the claim that the proposed semantics of [guard self]
cover the large majority of existing use cases of [weak self]
.