I'm faced with a lot of instances where I want to capture a parameter weakly in a closure and am forced to check if it exists before executing, and if not it becomes a non-op:
self.storedProperty.add(closure: { [weak self] in
guard let self=self else { return }
self.doStuff()
})
Often times these types of closures do not contain much code, which means for the sake of readability I have to turn a oneliner into at a minimum a threeliner — if you want to add a semicolon after the guard
.
An if
statement could work as well:
self.storedProperty.add(closure: { [weak self] in
if let self=self else { self.doStuff() }
})
But I just feel like there is a superior way that warrants consideration:
self.storedProperty.add(closure: { [weakStrong self] in self.doStuff() })
I think this latter syntax is very clear in its intent. We all know the 'weak/strong' dance. So simply using it literally as the reference modifier seems intuitive if that's what you're trying to do. In terms of simplicity, I think it's clear that all this does is only execute the closure if the weakStrong
reference exists. I don't know how difficult this would be to implement, but at some level, all it really would be doing is adding a guard
to check for the existence of the reference type at the beginning of the closure.
This appears to be a purely additive addition to the language. That said, I have seen a few posts that criticize capturing self
in the first place, and some that expressed entirely new ways of doing this sort of thing that syntactically, didn't even involve closures. I'm not aware of the path the Swift developers are taking in regards to this type of usage, but until it is traversed and we have that alternative — this is why I say "temporary" — I feel that this syntax offers a lot to be gained while requiring relatively little to gain it.