← 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.

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
func operate(_ a: Int, _ b: Int, using operation: (Int, Int) -> Int) -> Int {
    return operation(a, b)
}
let result = operate(5, 6) { x, y in
    x + y
}
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
let numbers = [3, 1, 4, 1, 5]
let doubled = numbers.map { $0 * 2 }
print(doubled)
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.