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.
In this page:
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
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)
Login to try C/C++/Java/PHP code in the editor
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
let numbers = [3, 1, 4, 1, 5]
let doubled = numbers.map { $0 * 2 }
print(doubled)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Placing the closure inside the parentheses out of habit, when Swift style favors moving it outside as a trailing closure.
- Forgetting that when a function's ONLY argument is a trailing closure, the parentheses can be omitted entirely.
- 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: