Trailing Closures / Shorthand / $0
In Swift, if the last argument of a function is a closure, you can use the "trailing closure" syntax to write it outside the parentheses. You can also use shorthand argument names like $0 and $1 for even more concise code.
Syntax
// Standard form
functionName(arg, closureArg: { body })
// Trailing closure
functionName(arg) { body }
// When the only argument is a closure (parentheses omitted)
functionName { body }
// $0 shorthand (omit parameter name)
functionName { $0 * 2 }
// Operator function (most concise)
[1,2,3].sorted(by: >)
Syntax Overview
| Syntax | Description |
|---|---|
| functionName() { body } | Moves the trailing closure argument outside the parentheses. |
| functionName { body } | When the closure is the only argument, you can omit the parentheses entirely. |
| $0, $1, $2 | Shorthand names that refer to closure arguments by position. |
| { $0 > $1 } | Shorthand form of a closure that compares two arguments. |
| sorted(by: >) | Passes an operator function in place of a closure. |
| map(\.property) | Passes a key path in place of a closure. |
Sample Code
let numbers = [3, 1, 4, 1, 5, 9, 2, 6]
// Standard form
let sorted1 = numbers.sorted(by: { (a: Int, b: Int) -> Bool in
return a < b
})
// Omit types using type inference
let sorted2 = numbers.sorted(by: { a, b in
return a < b
})
// Omit return (single expression)
let sorted3 = numbers.sorted(by: { a, b in a < b })
// $0 / $1 shorthand
let sorted4 = numbers.sorted(by: { $0 < $1 })
// Operator function (most concise)
let sorted5 = numbers.sorted(by: <)
print(sorted5) // [1, 1, 2, 3, 4, 5, 6, 9]
// Trailing closure
let doubled = numbers.map { $0 * 2 }
print(doubled) // [6, 2, 8, 2, 10, 18, 4, 12]
let evens = numbers.filter { $0 % 2 == 0 }
print(evens) // [4, 2, 6]
// Multiple trailing closures (Swift 5.3+)
func doAction(success: () -> Void, failure: () -> Void) {
success()
}
doAction {
print("Success!")
} failure: {
print("Failed...")
}
Notes
By combining trailing closure syntax with shorthand argument names, you can write Swift collection operations such as map, filter, and sorted very concisely.
$0 refers to the first closure argument, and $1 refers to the second. When there is only one argument, you typically use $0 alone. Overusing shorthand can reduce readability. For complex logic, using explicit argument names makes the code easier to understand.
For @escaping and capture lists, see @escaping / @autoclosure / Capture Lists.
If you find any errors or copyright issues, please contact us.