Explicit self not required for Task closures?

This strikes me as a problem somewhat different shape than the one that the implicit self capture rules are meant to solve. Those diagnostics are focused on trying to prevent common causes of strong reference cycles, namely, an instance of a reference type which (perhaps transitively) holds on to a strong reference to a closure which captures the original instance.

But the problem where the lifetime of captured state can get extended indefinitely in a non-terminating Task persists quite apart from any formal reference cycles. Indeed, this issue would persist even if you never held on to the returned Task object at all because it's the internal runtime machinery that keeps an executing Task alive, not the fact of any strong reference being held onto.

As you already note, the typical guard let self dance used to typically satisfy the compiler's complaints about self captures wouldn't be a sufficient mitigation here—you'd need to make sure you are dropping your strong self reference through every iteration of the loop. This has been discussed before here and here at the very least.

I think you're right that this pattern deserves better diagnostics but I'm not sure that simply falling back on the usual self capture rules are the right tool for the job.

3 Likes