Warnings on multiple access to weakly captured reference in same scope

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

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

Discourse needs a "laugh" react. :-)

5 Likes

Imho that's a job for a linter, not for the compiler.

2 Likes

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.