[swift-evolution] Making capturing semantics of local

Mike Kluev mike.kluev at gmail.com
Thu Oct 26 13:24:37 CDT 2017


On 26 October 2017 at 19:19, Mike Kluev <mike.kluev at gmail.com> wrote:

> on Wed, 25 Oct 2017 13:41:40 +0200 David Hart <david at hartbit.com> wrote:
>
> class A {
>>     func foo() {
>>         func local() {
>>             bar() // error: Call to method ‘bar' in function ‘local'
>> requires explicit 'self.' to make capture semantics explicit
>>         }
>>
>>         // ...
>>     }
>> }
>>
>
> it's not only about calling "bar"... any variable access will require
> self. which will be quite annoying, especially given the fact that "local"
> my not even be used in an escaping context discussed. (*)
>
> i think it is more consistent to prepend local with self if it is used in
> an escaping context:
>
> func foo() {
>
>     func local() {
>         bar()              // no self needed here ever
>         variable = 1   // no self needed here, ever
>     }
>
>     func otherLocal() {
>         print("i am not capturing self")
>     }
>
>     DispatchQueue.main.async {
>         local()            // error without self
>         self.local()       // ok
>         otherLocal()       // ok without self
>     }
> }
>
> (*) interestingly, closures always treat themselves as "escaping", even if
> it's not the case, e.g. even if i only use them in a non-escaping contexts.
> worth to add an explicit attribute to denote non-escaping closures?
>
> let closure = @nonescaping {
>     print("i am not escaping")
>     variable = 1 // ok without self
> }
>
> DispatchQueue.main.async(execute: closure) // error, non escaping closure
> passed
>
>
or, to keep the syntax close to the current one:

let closure = { nonescaping () -> Void in
     print("i am non escaping")
     variable = 1 // ok without self
}

with possible optimisations allowing omitting parameters / return values:

let closure = { nonescaping in
     print("i am non escaping")
     variable = 1 // ok without self
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171026/07934d3a/attachment.html>


More information about the swift-evolution mailing list