Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift optional escaping closure

enter image description here

Compiler error Closure use of non-escaping parameter 'completion' may allow it to escape, Which make sense because it will be called after the function return.

func sync(completion:(()->())) {
    self.remoteConfig.fetch(withExpirationDuration: TimeInterval(expirationDuration)) { (status, error) -> Void in
        completion()
    }
}

But if I make closure optional then no compiler error, Why is that? closure can still be called after the function returns.

func sync(completion:(()->())?) {
    self.remoteConfig.fetch(withExpirationDuration: TimeInterval(expirationDuration)) { (status, error) -> Void in
        completion?()
    }
}
like image 267
Bilal Avatar asked Nov 21 '17 16:11

Bilal


People also ask

Why optional closures are escaping?

It doesn't make sense to add escaping annotations to optional closures because they aren't function types: they are basically an enum (Optional) containing a function, the same way you would store a closure in any type: it's implicitly escaping because it's owned by another type.

What is an escaping closure Swift?

An escaping closure is a closure that's called after the function it was passed to returns. In other words, it outlives the function it was passed to. A non-escaping closure is a closure that's called within the function it was passed into, i.e. before it returns.

What is non-escaping closure in Swift?

In swift 5, closure parameters are non-escaping by default. Closures can also be executed within the function body; if we require escaping closure, we can mark it as @escaping. Closures can capture and store references to any constants and variables from the context in which they're defined.

How do you make a optional closure in Swift?

You should enclose the optional closure in parentheses. This will properly scope the ? operator. func then(onFulfilled: ()->(), onReject: (()->())?){ if let callableRjector = onReject { // do stuff! } }


1 Answers

Wrapping a closure in an Optional automatically marks it escaping. It's technically already "escaped" by being embedded into an enum (the Optional).

like image 169
Rob Napier Avatar answered Oct 04 '22 02:10

Rob Napier