[swift-users] Can't make an escaping closure argument optional?

Kevin Nattinger swift at nattinger.net
Fri Jan 5 14:04:25 CST 2018


If you remove the @escaping you'll notice it doesn't complain about a non-escaping closure escaping.
I could be wrong, but I believe that's because using it as an associated value forces it to escape on the calling side.

func esc(_ x: @escaping () -> ()) {
    x()
}
func noesc(_ x: () -> ()) {
    x()
}

func foo() {
    noesc {
        print(owner) // compiles
    }
    esc {
        print(owner) // error: requires explicit 'self.'…
    }
    Optional<()->()>.some {
        print(owner) // error: requires explicit 'self.'…
    }
}


> On Jan 5, 2018, at 11:48 AM, Kenny Leung via swift-users <swift-users at swift.org> wrote:
> 
> Hi All.
> 
> It seems that if you have an escaping closure argument, you can’t make it optional. Am I right?
>     init (
>         owner:AnyObject,
>         handler:@escaping (HXObserverNotification)->Void
>         ) {
>         self.owner = owner
>         self.handler = handler
>     }
> 
> You could try this:
>     init (
>         owner:AnyObject,
>         handler:@escaping ((HXObserverNotification)->Void)?
>         ) {
>         self.owner = owner
>         self.handler = handler
>     }
> You get “@escaping attribute only applies to function types”
> 
> Or you could try this:
>     init (
>         owner:AnyObject,
>         handler:(@escaping (HXObserverNotification)->Void)?
>         ) {
>         self.owner = owner
>         self.handler = handler
>     }
> You get “@escaping attribute may only be used in function parameter position”
> 
> -Kenny
> 
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20180105/98b31947/attachment.html>


More information about the swift-users mailing list