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

ilya ilya.nikokoshev at gmail.com
Tue Dec 8 09:59:55 CST 2015


Joe, a very good idea to allow directly capturing a value bound to an
immutable name without self keyword!
On Tue, Dec 8, 2015 at 18:55 Joe Groff via swift-evolution <
swift-evolution at swift.org> wrote:

>
> 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) }
>
>
> into:
>
> 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).
>
> -Joe
>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151208/33cd5a04/attachment.html>


More information about the swift-evolution mailing list