← Back to Swift Course | Chapter 7: Closures | Lesson 2 of 6

Trailing Closures

A trailing closure is a shortcut where, if a closure is the last argument to a function, you can write it outside the parentheses to make the call read more naturally.
Syntax
swift
functionName(argument) { param in
    // closure body
}

array.map { $0 transformation }   // parentheses dropped

Basic Trailing Closure Syntax

Instead of passing a closure inside the parentheses, it can be written directly after them when it's the function's last argument.

Example: Basic Trailing Closure Syntax

markup
// Define the function `operate` taking `a`, `b`, `operation` and returning an Int
func operate(_ a: Int, _ b: Int, using operation: (Int, Int) -> Int) -> Int {
    // Return `operation(a, b)` from this function
    return operation(a, b)
}
// Call `operate(5, 6)` with a trailing closure, storing the result in `result`
let result = operate(5, 6) { x, y in
    x + y
}
// Print `result` to the console
print(result)

Omitting Parentheses Entirely

When the closure is the function's only argument, the parentheses can be dropped completely, which is common with standard library methods.

Example: Omitting Parentheses Entirely

markup
// Declare a constant `numbers`, set to `[3, 1, 4, 1, 5]`
let numbers = [3, 1, 4, 1, 5]
// Declare a constant `doubled`, set to `numbers.map { $0 * 2 }`
let doubled = numbers.map { $0 * 2 }
// Print `doubled` to the console
print(doubled)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Placing the closure inside the parentheses out of habit, when Swift style favors moving it outside as a trailing closure.
  2. Forgetting that when a function's ONLY argument is a trailing closure, the parentheses can be omitted entirely.
  3. Confusing multiple trailing closures (Swift 5.3+) syntax, where subsequent closures need their own labels.
Chapter Summary
  • When a closure is a function's final argument, it can be written after the closing parenthesis.
  • If the closure is the only argument, the parentheses can be dropped entirely.
  • This produces cleaner, more readable code for functions like .map, .filter, and .sorted(by:).
  • Multiple trailing closures are supported since Swift 5.3, each requiring its own label after the first.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.