0
0
Swiftprogramming~3 mins

Why Escaping closures (@escaping) in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app could remember to finish tasks even after the function is gone? That's the magic of escaping closures!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
func loadData(completion: () -> Void) {
    // Can't run completion after function ends
}

loadData {
    print("Done")
}
After
func loadData(completion: @escaping () -> Void) {
    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
        completion()
    }
}

loadData {
    print("Done")
}
What It Enables

It enables your app to handle tasks that finish later, like network calls or animations, without losing track of what to do next.

Real Life Example

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.

Key Takeaways

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.