Junior — Middle
Is a completion block considered a class field in terms of escaping or non-escaping?
sobes.tech AI
Answer from AI
In the context of Swift and iOS development, a completion block that is a class property is considered an escaping closure. This is because the block may be called after the function it was passed to has exited, for example, asynchronously.
If a completion block is passed to a function and called synchronously within it, it is non-escaping by default.
Example:
class MyClass {
var completion: (() -> Void)? // escaping closure, as it is stored in a property
func doSomething() {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.completion?() // called after a delay
}
}
}
Here, completion is escaping because it is called later, outside the context of the function call.