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

Closure Shorthand Syntax

Closure shorthand is Swift's way of letting you write a closure with fewer words once the context already makes things obvious.

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

markup
let numbers = [4, 2, 7, 1]
let sorted = numbers.sorted { a, b in a < b }
print(sorted)

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

markup
let numbers = [4, 2, 7, 1]
let doubled = numbers.map { $0 * 2 }
let sorted = numbers.sorted { $0 < $1 }
print(doubled)
print(sorted)

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

markup
let numbers = [4, 2, 7, 1]
let descending = numbers.sorted(by: >)
print(descending)
Common Mistakes
  1. Overusing $0, $1 shorthand for closures with complex logic, hurting readability; shorthand is best for short, simple closures.
  2. Writing return in a single-expression closure body; it's implicit and optional there but required in multi-statement closures.
  3. Forgetting operator functions like + or > can be passed directly as a closure when their signature matches exactly.
Chapter Summary
  • 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 return keyword.
  • 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:

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.