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?()
}
}
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.
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.
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.
You should enclose the optional closure in parentheses. This will properly scope the ? operator. func then(onFulfilled: ()->(), onReject: (()->())?){ if let callableRjector = onReject { // do stuff! } }
Wrapping a closure in an Optional automatically marks it escaping. It's technically already "escaped" by being embedded into an enum (the Optional).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With