Bird
Raised Fist0
Swiftprogramming~10 mins

Escaping closures (@escaping) in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Escaping closures (@escaping)
Define function with closure parameter
↓
Is closure marked @escaping?
↓
Closure can escape
↓
Store closure
↓
Function returns
↓
Closure called later
This flow shows how a closure marked @escaping can be stored and called after the function returns, while non-escaping closures run immediately inside the function.
Execution Sample
Swift
var completionHandlers: [() -> Void] = []

func doAsyncTask(completion: @escaping () -> Void) {
    completionHandlers.append(completion)
}

doAsyncTask {
    print("Task done")
}
This code stores an escaping closure in an array to be called later, simulating an asynchronous task.
Execution Table
StepActionState of completionHandlersOutput
1Define empty array completionHandlers[]
2Call doAsyncTask with closure[]
3Inside doAsyncTask, append closure to completionHandlers[closure]
4doAsyncTask returns[closure]
5Closure not called yet[closure]
6Call closure from completionHandlers[0][closure]Task done
💡 Execution stops after closure is called and prints output.
Variable Tracker
VariableStartAfter Step 3After Step 6
completionHandlers[][closure][closure]
Key Moments - 3 Insights
Why do we need @escaping for the closure parameter?
Because the closure is stored in completionHandlers and called after the function returns, it escapes the function scope. The execution_table row 3 shows the closure being appended and stored.
What happens if we don't mark the closure as @escaping?
The compiler will give an error because the closure is used after the function returns, which is not allowed for non-escaping closures. This is implied by the flow in concept_flow.
When is the closure actually executed?
The closure is executed later when we call completionHandlers[0]() as shown in execution_table step 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of completionHandlers after step 3?
AIt is still empty
BIt contains two closures
CIt contains one closure
DIt is nil
💡 Hint
Check the 'State of completionHandlers' column at step 3 in execution_table.
At which step does the closure actually print 'Task done'?
AStep 4
BStep 6
CStep 2
DStep 1
💡 Hint
Look at the 'Output' column in execution_table to find when 'Task done' is printed.
If the closure parameter was not marked @escaping, what would happen?
AThe compiler would give an error
BThe closure would run twice
CThe closure could still be stored and called later
DThe closure would run immediately
💡 Hint
Refer to key_moments question about the need for @escaping.
Concept Snapshot
Escaping closures (@escaping):
- Mark closure parameters with @escaping if stored or called after function returns.
- Non-escaping closures run immediately inside the function.
- Escaping closures can be stored and called later.
- Compiler enforces @escaping to avoid unsafe use.
- Use @escaping for async callbacks or delayed execution.
Full Transcript
This visual execution trace shows how escaping closures work in Swift. We start with an empty array to store closures. When we call a function with an @escaping closure parameter, the closure is appended to the array and the function returns. The closure is not executed immediately but stored for later use. Later, when we call the closure from the array, it runs and prints output. The key point is that @escaping allows the closure to live beyond the function call. Without @escaping, the compiler would prevent storing the closure. This trace helps beginners see step-by-step how escaping closures behave.

Practice

(1/5)
1. What does the @escaping keyword indicate in Swift closures?
easy
A. The closure can be called after the function returns
B. The closure is executed immediately within the function
C. The closure cannot capture variables from the surrounding scope
D. The closure is only used for synchronous tasks

Solution

  1. Step 1: Understand closure execution timing

    Closures without @escaping run inside the function before it returns.
  2. Step 2: Role of @escaping

    Marking a closure @escaping means it can be stored and called later, after the function ends.
  3. Final Answer:

    The closure can be called after the function returns -> Option A
  4. Quick Check:

    @escaping means delayed closure call [OK]
Hint: Escaping closures run later, not immediately [OK]
Common Mistakes:
  • Thinking @escaping closures run immediately
  • Confusing @escaping with synchronous execution
  • Believing @escaping closures cannot capture variables
2. Which of the following is the correct syntax to declare a function parameter as an escaping closure in Swift?
easy
A. func fetchData(completion: () -> Void) {}
B. func fetchData(completion: escaping () -> Void) {}
C. func fetchData(@escaping completion: () -> Void) {}
D. func fetchData(completion: @escaping () -> Void) {}

Solution

  1. Step 1: Identify correct placement of @escaping

    The @escaping keyword must appear before the closure type in the parameter list.
  2. Step 2: Check each option's syntax

    func fetchData(completion: @escaping () -> Void) {} correctly places @escaping before the closure type. Options A, C, and D have incorrect syntax.
  3. Final Answer:

    func fetchData(completion: @escaping () -> Void) {} -> Option D
  4. Quick Check:

    Correct syntax = func fetchData(completion: @escaping () -> Void) {} [OK]
Hint: Put @escaping before the closure type in parameters [OK]
Common Mistakes:
  • Placing @escaping before parameter name
  • Omitting @escaping for delayed closures
  • Writing 'escaping' without @ symbol
3. What will be the output of the following Swift code?
func performTask(completion: @escaping () -> Void) {
    DispatchQueue.main.async {
        completion()
    }
    print("Task started")
}

performTask {
    print("Task completed")
}
medium
A. Task started
B. Task completed\nTask started
C. Task started\nTask completed
D. Task completed

Solution

  1. Step 1: Understand async dispatch behavior

    The closure passed to DispatchQueue.main.async runs later, after the current function finishes.
  2. Step 2: Trace print statements order

    "Task started" prints immediately. Then the closure runs and prints "Task completed".
  3. Final Answer:

    Task started\nTask completed -> Option C
  4. Quick Check:

    Async closure runs after print [OK]
Hint: Async closures run after current code finishes [OK]
Common Mistakes:
  • Assuming closure runs before print
  • Ignoring async dispatch delay
  • Confusing order of print statements
4. Identify the error in this Swift function using an escaping closure:
func saveData(completion: () -> Void) {
    DispatchQueue.global().async {
        // Save operation
        completion()
    }
}
medium
A. Missing @escaping before closure parameter
B. Closure parameter should be optional
C. DispatchQueue.global() cannot be used here
D. Completion closure must return a value

Solution

  1. Step 1: Analyze closure usage inside async block

    The closure is called asynchronously after the function returns, so it must be marked @escaping.
  2. Step 2: Check function parameter declaration

    The parameter lacks @escaping, causing a compile error.
  3. Final Answer:

    Missing @escaping before closure parameter -> Option A
  4. Quick Check:

    Async closure needs @escaping [OK]
Hint: Async closure parameters must be @escaping [OK]
Common Mistakes:
  • Forgetting @escaping for async closures
  • Assuming closure is synchronous by default
  • Adding unnecessary optional to closure
5. You want to store a closure to call later after a network request finishes. Which is the correct way to declare and use this escaping closure in Swift?
class NetworkManager {
    var completionHandler: (() -> Void)?

    func requestData(completion: ???) {
        self.completionHandler = completion
        // Simulate network delay
        DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
            self.completionHandler?()
        }
    }
}
hard
A. completion: () -> Void
B. completion: @escaping () -> Void
C. completion: @autoclosure () -> Void
D. completion: @escaping @autoclosure () -> Void

Solution

  1. Step 1: Understand closure storage and delayed call

    The closure is saved in a property and called later asynchronously, so it must be @escaping.
  2. Step 2: Evaluate options for closure parameter

    Only completion: @escaping () -> Void correctly marks the closure as @escaping. Options A, B, and D are incorrect or unnecessary here.
  3. Final Answer:

    completion: @escaping () -> Void -> Option B
  4. Quick Check:

    Stored closures must be @escaping [OK]
Hint: Store closures? Use @escaping keyword [OK]
Common Mistakes:
  • Omitting @escaping when storing closures
  • Using @autoclosure unnecessarily
  • Marking closure without @escaping for delayed call
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard