What if your app could remember to finish tasks even after the function is gone? That's the magic of escaping closures!
Why Escaping closures (@escaping) in Swift? - Purpose & Use Cases
Imagine you want to run some code later, like after downloading a photo from the internet. You try to write that code inside a function, but the function ends before the download finishes.
Without a way to keep that code alive, your program forgets what to do next. This makes your app stop or crash because it tries to use something that no longer exists.
Escaping closures let you tell Swift: "Hey, keep this code safe and run it later, even after the function ends." This way, your app waits patiently and works smoothly.
func loadData(completion: () -> Void) {
// Can't run completion after function ends
}
loadData {
print("Done")
}func loadData(completion: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
completion()
}
}
loadData {
print("Done")
}It enables your app to handle tasks that finish later, like network calls or animations, without losing track of what to do next.
When you tap a button to fetch weather info, escaping closures let your app wait for the data and then update the screen once it arrives.
Without escaping closures, delayed code can't run properly.
@escaping tells Swift to keep the closure alive beyond the function.
This makes asynchronous tasks safe and smooth in your app.