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

Andrew Bennett cacoyi at gmail.com
Tue Dec 8 05:15:32 CST 2015


>From 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?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151208/5ff9b8d9/attachment.html>


More information about the swift-evolution mailing list