Junior — Middle
Explain what the term 'escaping closure' means in the context of programming.
sobes.tech AI
Answer from AI
In programming, especially in Swift for iOS, the term "escaping closure" refers to a closure that can be called after the function accepting it has already finished executing.
By default, closures in Swift are considered "non-escaping" — they must be called within the body of the function. If a closure is stored for later use (for example, asynchronously), it needs to be marked as @escaping.
Example:
func performAsyncTask(completion: @escaping () -> Void) {
DispatchQueue.global().async {
// some work
completion() // called later, after the function exits
}
}
Here, completion is an escaping closure because it is called asynchronously after performAsyncTask has finished.