I've never really understood when to use @escaping
in Swift. I understand what it does (i.e. the difference between escaping and non-escaping closures), but tbf I've always been relying on Xcode to tell me when to add the modifier to my argument.
My question is, why is it the case that @escaping
only applies to non-nil closures? This is what I mean:
func someFunc(someArg: Int, callback: @escaping (Error?) -> Void) {
DispatchQueue.global(qos: .background).async {
...
}
}
In the above, if I don't add @escaping
Xcode gives me an error. However, if I make callback
optional like the following, keeping @escaping
results in Xcode error:
// This is wrong (Xcode complains about @escaping)
func someFunc(someArg: Int, callback: @escaping ((Error?) -> Void)?) {
DispatchQueue.global(qos: .background).async {
...
}
}
Why is that? Thank you!