Escaping closures let you use a piece of code later, even after the function that got it finishes. This helps when you want to do something after waiting or in the background.
0
0
Escaping closures (@escaping) in Swift
Introduction
When you want to run code after a delay or asynchronously, like fetching data from the internet.
When you store a closure to use it later, for example in a completion handler.
When you pass a closure to a function but it might be called after the function returns.
When you want to keep a closure around for event handling or callbacks.
Syntax
Swift
func someFunction(completion: @escaping () -> Void) { // function body }
The @escaping keyword tells Swift the closure might be called later, not immediately.
Without @escaping, the closure must be used before the function ends.
Examples
This example shows a closure that runs after 1 second, so it must be marked
@escaping.Swift
func performTask(completion: @escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + 1) { completion() } }
This closure runs immediately, so
@escaping is not needed.Swift
func saveData(completion: () -> Void) {
completion()
}Sample Program
This program simulates fetching data asynchronously. The closure is marked @escaping because it runs after the function returns. The program waits 3 seconds to show the result.
Swift
import Foundation func fetchData(completion: @escaping (String) -> Void) { DispatchQueue.global().async { // Simulate network delay sleep(2) let data = "Hello from network" DispatchQueue.main.async { completion(data) } } } print("Start fetching...") fetchData { result in print("Received: \(result)") } // Keep the program running to see async result RunLoop.main.run(until: Date(timeIntervalSinceNow: 3))
OutputSuccess
Important Notes
Use @escaping only when the closure is called after the function returns.
Escaping closures can capture variables and keep them alive longer.
Be careful with retain cycles when using escaping closures inside classes.
Summary
Escaping closures run after the function ends.
Mark closures with @escaping if they run later or asynchronously.
They help with callbacks, delays, and asynchronous tasks.