[swift-evolution] [Pitch] Introduction of `weak/unowned` closures

Greg Parker gparker at apple.com
Tue Jun 13 17:39:49 CDT 2017

> On Jun 10, 2017, at 2:42 PM, Paul Cantrell via swift-evolution <swift-evolution at swift.org> wrote:
> Being able to specify things about closure capturing at the API level could do wonders for Siesta — though its problems may be beyond the scope of what’s proposed here (or what’s workable at all).
> Siesta exposes this API call:
>     someResource.addObserver(owner: self) {  // (1)
>         [weak self] resource, event in
>>         self.bar()
>>     }
> …but it’s easy to forget that [weak self], and because of Siesta’s observer ownership rules:
>     http://bustoutsolutions.github.io/siesta/guide/memory/ <http://bustoutsolutions.github.io/siesta/guide/memory/>
> …omitting it creates a retain cycle. This same problem also makes this otherwise lovely pattern untenable:
>     someResource.addObserver(owner: self, closure: self.fooUpdated) // (2)
> To solve this problem, addObserver would need to be able to specify that the object passed as the owner should be weakly captured by the closure. It’s just that one specific •owner• object; everything else should be captured as usual. So it’s not a property of the closure itself, either in the type system or as an argument attribute; it’s a relationship between the closure and other args. Ouch!

One way to allow the closure's caller to control the memory management of a value in the closure is to make that value a parameter of the closure rather than a capture.

In this example addObserver() could store the owner in a weak variable and pass it to the closure when called.

    someResource.addObserver(owner: self) {
        owner, resource, event in

Greg Parker     gparker at apple.com <mailto:gparker at apple.com>     Runtime Wrangler

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170613/c6c51fa6/attachment.html>

More information about the swift-evolution mailing list