Bird
Raised Fist0
Swiftprogramming~10 mins

Trailing closure syntax in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Trailing closure syntax
Call function with closure
↓
Is closure last argument?
No→Use normal closure syntax
Yes↓
Use trailing closure syntax
↓
Execute closure body
↓
Return from function
This flow shows how Swift decides to use trailing closure syntax when the closure is the last argument in a function call.
Execution Sample
Swift
func greet(action: () -> Void) {
    print("Start")
    action()
    print("End")
}

greet {
    print("Hello from closure")
}
This code calls a function with a trailing closure that prints a message between two prints.
Execution Table
StepActionOutputNotes
1Call greet with trailing closureStartFunction starts, prints 'Start'
2Execute closure bodyHello from closureClosure prints its message
3Continue greet functionEndFunction prints 'End'
4Function returnsExecution ends
💡 Function completes after printing 'End' and returning
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
actionclosure passedclosure readyclosure executedclosure donefunction done
Key Moments - 2 Insights
Why can we omit parentheses when using trailing closure syntax?
Because the closure is the last argument, Swift allows omitting parentheses and writing the closure outside the parentheses, as shown in step 1 of the execution_table.
What happens if the closure is not the last argument?
Trailing closure syntax cannot be used; the closure must be inside the parentheses, as explained in the concept_flow decision step.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is printed at Step 2?
A"Start"
B"End"
C"Hello from closure"
DNothing
💡 Hint
Check the Output column for Step 2 in the execution_table
At which step does the function print "End"?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the Output column in the execution_table for when "End" is printed
If the closure was not the last argument, what would change in the code?
AWe must write the closure inside parentheses
BWe could still use trailing closure syntax
CThe closure would be ignored
DThe function would not compile
💡 Hint
Refer to the concept_flow decision about closure position
Concept Snapshot
Trailing closure syntax lets you write a closure outside the parentheses if it is the last argument.
Syntax: functionName { closureBody }
Use it to make code cleaner and more readable.
If closure is not last, write it inside parentheses.
Swift automatically associates the trailing closure with the last parameter.
Full Transcript
Trailing closure syntax in Swift allows you to write a closure argument outside the parentheses when it is the last argument in a function call. The example shows a function greet that takes a closure. When calling greet, the closure is written after the parentheses, making the code cleaner. The execution steps show the function printing "Start", then the closure prints "Hello from closure", and finally the function prints "End" before returning. This syntax is only allowed if the closure is the last argument. If not, the closure must be inside the parentheses.

Practice

(1/5)
1. What does trailing closure syntax allow you to do in Swift?
func perform(action: () -> Void) { action() }
easy
A. Write the last closure argument outside the parentheses
B. Use closures only inside parentheses
C. Avoid using closures altogether
D. Write closures only as named functions

Solution

  1. Step 1: Understand closure arguments in Swift functions

    Swift functions can take closures as arguments, usually inside parentheses.
  2. Step 2: Identify trailing closure syntax purpose

    Trailing closure syntax lets you write the last closure argument outside the parentheses for cleaner code.
  3. Final Answer:

    Write the last closure argument outside the parentheses -> Option A
  4. Quick Check:

    Trailing closure syntax = last closure outside parentheses [OK]
Hint: Last closure can go outside parentheses for clarity [OK]
Common Mistakes:
  • Thinking closures must always be inside parentheses
  • Confusing trailing closures with named functions
  • Believing trailing closures remove closures entirely
2. Which of the following is the correct way to use trailing closure syntax in Swift?
func greet(action: () -> Void) { action() }
easy
A. greet() { print("Hello") }
B. greet { print("Hello") }
C. greet { print("Hello") }()
D. greet(print("Hello"))

Solution

  1. Step 1: Recall trailing closure syntax format

    Trailing closure syntax allows calling a function with a closure outside parentheses if it's the last argument.
  2. Step 2: Check each option

    greet { print("Hello") } correctly calls greet with closure outside parentheses: greet { print("Hello") }.
  3. Final Answer:

    greet { print("Hello") } -> Option B
  4. Quick Check:

    Trailing closure syntax = function { closure } [OK]
Hint: Use braces after function name without parentheses for trailing closure [OK]
Common Mistakes:
  • Adding empty parentheses before trailing closure
  • Trying to call closure immediately with () after braces
  • Passing closure as a normal argument inside parentheses
3. What is the output of this Swift code?
func repeatTask(times: Int, task: () -> Void) {
    for _ in 1...times { task() }
}

repeatTask(times: 3) {
    print("Hi")
}
medium
A. Hi Hi Hi
B. Hi Hi Hi
C. Hi Hi
D. Error: Missing parentheses

Solution

  1. Step 1: Understand repeatTask function behavior

    The function calls the closure 'task' the number of times specified by 'times'. Here, times = 3.
  2. Step 2: Analyze the closure call

    The closure prints "Hi" each time. So it prints "Hi" three times, each on a new line because print adds a newline.
  3. Final Answer:

    Hi Hi Hi -> Option A
  4. Quick Check:

    3 prints of "Hi" each on new line = Hi Hi Hi [OK]
Hint: print adds newline, so repeated prints appear on separate lines [OK]
Common Mistakes:
  • Assuming prints appear on same line without newline
  • Thinking trailing closure causes syntax error
  • Confusing number of repetitions
4. Identify the error in this Swift code using trailing closure syntax:
func calculate(operation: (Int, Int) -> Int) {
    let result = operation(5, 3)
    print(result)
}

calculate() { (a, b) in
    a + b
}
medium
A. Trailing closure syntax cannot be used here
B. Missing return keyword inside closure
C. Closure parameters should be outside parentheses
D. Extra parentheses after calculate() when using trailing closure

Solution

  1. Step 1: Check function call syntax with trailing closure

    When using trailing closure syntax, do not include empty parentheses before the closure.
  2. Step 2: Identify the error in code

    The code calls calculate() with empty parentheses and then a trailing closure, which is incorrect syntax.
  3. Final Answer:

    Extra parentheses after calculate() when using trailing closure -> Option D
  4. Quick Check:

    Trailing closure means no parentheses if no other arguments [OK]
Hint: Remove empty parentheses when using trailing closure [OK]
Common Mistakes:
  • Including empty parentheses before trailing closure
  • Adding unnecessary return in single-expression closure
  • Thinking trailing closure can't have parameters
5. Given this Swift function:
func fetchData(completion: (String) -> Void) {
    let data = "User info"
    completion(data)
}

How would you call fetchData using trailing closure syntax to print the data received?
hard
A. fetchData() { data in print(data) }
B. fetchData(completion: { data in print(data) })
C. fetchData { data in print(data) }
D. fetchData { print(data) }

Solution

  1. Step 1: Understand trailing closure syntax for single closure argument

    When the last argument is a closure, you can write it outside parentheses without empty parentheses.
  2. Step 2: Check each option for correct syntax and usage

    fetchData { data in print(data) } correctly calls fetchData with trailing closure and closure parameter 'data' used inside print.
  3. Final Answer:

    fetchData { data in print(data) } -> Option C
  4. Quick Check:

    Trailing closure with parameter = fetchData { data in print(data) } [OK]
Hint: Write closure after function name without parentheses for trailing closure [OK]
Common Mistakes:
  • Including empty parentheses before trailing closure
  • Omitting closure parameter when needed
  • Trying to use closure inside parentheses and trailing closure simultaneously
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