Junior — Middle
Kas on vajalik, et kasutada escape-mehhanismi funktsiooni argumentidena edastatud sulgemiste jaoks?
sobes.tech AI
Vastus AI-lt
In Swift, closures are non-escaping by default, meaning they cannot be stored and called after the function they are passed to has finished.
If you need to store and call the closure later (for example, in an asynchronous call, callback), you must mark it as @escaping.
Example:
func performAsyncTask(completion: @escaping () -> Void) {
DispatchQueue.global().async {
// some work
completion() // call later
}
}
If the closure is only used inside the function and not stored, @escaping is not needed.
Therefore, the escaping mechanism should be used only when the closure can be called after the function it was passed to has exited.