Is there already some compiler flag that allows this warning, otherwise what would be the best way to pitch this behavior?
When encountering code like:
{ [weak self] in
self?.prepare()
self?.doWork()
self?.cleanup()
}
I'd like the compiler to emit a warning, and offer a fixit that creates a strong reference that persists throughout the scope.
Thanks in advance for any suggestions on how to pursue pitching this or how to access any existing flags.
4 Likes
jrose
(Jordan Rose)
2
Oof. We have that warning in Clang, but we should certainly have it in Swift as well. For any new warning, though, it's important to have a way to silence it to say "yes, I really do want to recheck self for each of these calls."
5 Likes
A definitely terrible way to signal that you want to silence the warning would be to chain multiple calls to self. This is legal:
{ [weak self] in
self?.self.prepare()
self?.self.doWork()
self?.self.cleanup()
}
The fixit could suggest that, and the compiler could use it to infer that you actually meant to have the separate references. But please, please don't solve it like this. I regret posting it, and I haven't even hit the button yet.
1 Like
jrose
(Jordan Rose)
4
Discourse needs a "laugh" react. :-)
5 Likes
Tino
(Tino)
5
Imho that's a job for a linter, not for the compiler.
2 Likes
Jon_Shier
(Jon Shier)
6
I do this to encapsulate long promise chains that need many weak captures. It works pretty well, but I wouldn't do it for synchronous work, just closures.