[swift-evolution] Proposal: Closures capture weak by default

Joe Groff jgroff at apple.com
Tue Dec 8 09:55:21 CST 2015

> On Dec 8, 2015, at 7:49 AM, Joe Groff <jgroff at apple.com> wrote:
> Capturing weak by default is not safe. ARC optimization will shrinkwrap the lifetimes of strong references to their last strong use, so capturing a local variable that references a fresh object would cause the object to immediately go away:
> let x = NSObject()
> dispatch_sync {[weak x] in x!.foo() } // x can already be gone by this point
> There's no one right answer here.

One reason cycles are so prevalent with closures is that it's easy to capture too much, since referencing 'self.foo' always captures the entirety of 'self'. If the properties of 'self' you need are immutable, or you don't need to see their mutations, you can reduce the risk of cycles by capturing those properties explicitly, turning this:

self.setCallback { doStuffWith(self.zim, self.zang) }


self.setCallback {[zim, zang] in doStuffWith(zim, zang) }

For 'let' properties of classes, it'd be reasonable to propose having closures capture the *property* directly by default in this way instead of capturing 'self' (and possibly allowing referencing them without 'self.', since 'self' wouldn't be involved in any cycle formed this way).


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

More information about the swift-evolution mailing list