Closure Shorthand Syntax
In this page:
Type Inference and Implicit Return
When Swift already knows a closure's expected type from context, the closure can drop explicit types and the return keyword for a single expression.
Example: Type Inference and Implicit Return
let numbers = [4, 2, 7, 1]
let sorted = numbers.sorted { a, b in a < b }
print(sorted)
Login to try C/C++/Java/PHP code in the editor
Shorthand Argument Names
Swift automatically provides $0, $1, etc. as names for a closure's parameters, letting you skip naming them entirely for short closures.
Example: Shorthand Argument Names
let numbers = [4, 2, 7, 1]
let doubled = numbers.map { $0 * 2 }
let sorted = numbers.sorted { $0 < $1 }
print(doubled)
print(sorted)
Login to try C/C++/Java/PHP code in the editor
Passing an Operator as a Closure
When an operator's signature matches the expected closure type exactly, it can be passed directly by name instead of writing out a closure.
Example: Passing an Operator as a Closure
let numbers = [4, 2, 7, 1]
let descending = numbers.sorted(by: >)
print(descending)
Login to try C/C++/Java/PHP code in the editor
- Overusing
$0,$1shorthand for closures with complex logic, hurting readability; shorthand is best for short, simple closures. - Writing
returnin a single-expression closure body; it's implicit and optional there but required in multi-statement closures. - Forgetting operator functions like
+or>can be passed directly as a closure when their signature matches exactly.
- Swift can infer parameter and return types in a closure passed to a known function signature.
$0,$1, etc. refer to a closure's parameters positionally without naming them.- A single-expression closure body can omit the
returnkeyword. - Operators like
+,<, or>can be passed directly as closures matching a two-parameter function type.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: