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

Joe Groff jgroff at apple.com
Tue Dec 8 09:49:27 CST 2015


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.

-Joe

> On Dec 8, 2015, at 3:15 AM, Andrew Bennett via swift-evolution <swift-evolution at swift.org> wrote:
> 
> From https://swift.org/about/ <https://swift.org/about/>: "The most obvious way to write code should also behave in a safe manner."
> 
> To this end I think that closures should capture references types weakly by default. Pretty much the only way I know of to (easily) create memory issues with pure swift is to capture a strong reference in a closure.
> 
> I think with consideration when designing asynchronous APIs this could be quite painless.
> 
> Cases weak may be excluded:
>  * If the closure is @noescape
>  * If the object's lifetime is provably limited to the block
>  * If it's a value type
> 
> I think the upsides by far outweigh the downsides.
> 
> Upside:
>  * no more surprises
>  * safer code
> 
> Downsides:
>  * You may sometimes have to use optional chaining or similar to resolve a weak reference.
>  * Beginners need to understand optionals, but they're likely to do so before learning blocks.
>  * There's probably a few edge cases I haven't explored, and a few more here:
> 
> class Test {
>    func doSomething(v: Int) { ... }
>    func async(callback: Int->Void) {
>       doWork { value in
>            callback?(value)
>       }
>    }
> }
> 
> self.test = Test()
> self.test.async(test.doSomething) // what is the lifetime of test.doSomething?
> 
>  _______________________________________________
> 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/86111f45/attachment.html>


More information about the swift-evolution mailing list