What does 0 and 1 mean in Swift Closures?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In Swift closures, $0, $1, $2, and so on are shorthand names for the closure's parameters. They let you write small closures without explicitly naming the arguments, which is convenient when the meaning is obvious from context.
What $0 and $1 Refer To
The numbering is positional:
- '
$0is the first parameter' - '
$1is the second parameter' - '
$2is the third parameter'
For example, in a closure passed to sorted, there are two arguments being compared:
Here, $0 and $1 are the two elements that sorted asks the closure to compare.
Why the Syntax Exists
Swift closures can be written in a very compact style. If you had to name every argument every time, short collection transformations would become noisy.
Compare these two versions:
Both produce the same result. The second version is shorter because Swift infers the parameter list and provides $0 automatically.
Swift can do this because the surrounding API already tells the compiler what kind of closure is expected. The shorthand names are part of that inference story, not a separate variable system.
When Shorthand Works Well
Shorthand arguments are best when:
- the closure body is short
- the parameter meaning is obvious
- there are only one or two inputs
Collection helpers are a common example:
In those cases, the shorthand reads naturally once you know the rule.
When Explicit Names Are Better
The shorthand is optional. If the closure is complex, explicit names are usually easier to read:
Using $0 and $1 here would work, but it would make the logic harder to follow. Clear parameter names often matter more than saving a few characters.
Another important point is that $0 and $1 do not come from surrounding scope. They are generated by Swift only for that closure's implicit parameters.
Common Pitfalls
One common mistake is thinking $0 is always the first element of an array. It is not. It is simply the first argument passed into the current closure.
Another issue is overusing shorthand in long or nested closures. Code that was concise at first can become much harder to understand once several anonymous parameters are involved.
It is also easy to forget how many arguments a closure receives. Some APIs pass one value, some pass two, and others pass none. The closure signature decides whether $0, $1, or additional shorthand names even exist.
Summary
- '
$0, $1, and similar names are shorthand closure parameters in Swift.' - '
$0refers to the first argument, $1to the second, and so on.' - They are most useful in short, obvious closures such as
map,filter, andsorted. - Explicit parameter names are often better for multi-line or more complex logic.
- The shorthand names belong only to the current closure and are based on that closure's parameter list.

