Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A trailing closure is syntactic sugar in Swift that allows a closure expression to be written outside and immediately following the parentheses of a function call. This syntax is applicable when the closure is the final argument in the function’s parameter list, reducing visual clutter by preventing deep nesting of braces within parentheses. When utilizing a trailing closure, the argument label for that specific closure parameter is omitted from the function call.

Single Trailing Closure

Given a function where the final parameter expects a closure:
func executeOperation(identifier: String, completion: () -> Void) {
    // Function body
}
Standard Call (Inline Closure): The closure is passed inside the parentheses, requiring the argument label.
executeOperation(identifier: "Task-1", completion: {
    print("Operation complete")
})
Trailing Closure Call: The closure is moved outside the parentheses, and the completion argument label is dropped.
executeOperation(identifier: "Task-1") {
    print("Operation complete")
}

Omitting Parentheses

If the function requires only a closure as its single argument, the execution parentheses () can be entirely omitted from the function call.
func delayExecution(action: () -> Void) {
    // Function body
}

// Parentheses omitted entirely
delayExecution {
    print("Executing delayed action")
}

Multiple Trailing Closures

Introduced in Swift 5.3, if a function accepts multiple closures as its final consecutive parameters, you can use multiple trailing closure syntax. In this structure:
  1. The first trailing closure omits its argument label.
  2. All subsequent trailing closures are chained immediately after the first and must include their respective argument labels.
func fetchResource(
    url: String, 
    onSuccess: (String) -> Void, 
    onFailure: (Error) -> Void
) {
    // Function body
}
Multiple Trailing Closure Call:
fetchResource(url: "https://api.example.com/data") { response in
    // First trailing closure (label 'onSuccess' is omitted)
    print("Success: \(response)")
} onFailure: { error in
    // Subsequent trailing closure (label 'onFailure' is required)
    print("Failed with error: \(error)")
}
Master Swift with Deep Grasping Methodology!Learn More