[swift-evolution] Making capturing semantics of local functions explicit

Tony Allevato tony.allevato at gmail.com
Wed Oct 25 14:13:39 CDT 2017


Does the compiler treat a nested function differently from a closure in any
meaningful way? (I suppose they might have symbols emitted in the symbol
table, whereas a closure assigned to a local variable wouldn't?)

It definitely seems odd that you can write two functionally equivalent
pieces of code (one with a closure, one with a nested function) and can
only address the capturing semantics in one of them. Unifying these seems
like a good idea.

On Wed, Oct 25, 2017 at 10:12 AM David Sweeris via swift-evolution <
swift-evolution at swift.org> wrote:

>
> On Oct 25, 2017, at 4:41 AM, David Hart via swift-evolution <
> swift-evolution at swift.org> wrote:
>
> I got bit again by a sneaky memory leak concerning local functions and
> would like to discuss a small language change. I vaguely remember this
> being discussed in the past, but can’t find the thread (if anybody could
> point me to it, I’d appreciate it). Basically, here’s an example of the
> leak:
>
> class A {
>     func foo() {
>         func local() {
>             bar()
>         }
>
>         methodWithEscapingClosure { [unowned self] _ in
>             self.bar()
>             local() // this leaks because local captures self        }
>     }
>
>     func bar() {
>     }
> }
>
>
> Its sneaky because local’s capturing of self is not obvious if you’ve
> trained your brain to watch out for calls prefixed with self. I would
> suggest having the compiler force users to make self capturing explicit,
> the same way it does for closures:
>
> class A {
>     func foo() {
>         func local() {
>             bar() // error: Call to method ‘bar' in function ‘local' requires explicit 'self.' to make capture semantics explicit
>         }
>     	// ...
>     }
> }
>
>
> What do you think?
>
>
> Works for me
>
> - Dave Sweeris
>
> _______________________________________________
> 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/20171025/6fd01a3f/attachment.html>


More information about the swift-evolution mailing list