I have seen closures in Swift use $0
internally and sometimes they use $1
. What exactly is $0
and what are other $X
can you use?
Here are examples of it in use:
applyMutliplication(2, {$0 * 3}) array.map({$0 + 1})
So the . 0 means the first or zeroth element of the tuple and . 1 means the second element.
In Swift, a closure is a special type of function without the function name. For example, { print("Hello World") } Here, we have created a closure that prints Hello World .
There are two kinds of closures: An escaping closure is a closure that's called after the function it was passed to returns. In other words, it outlives the function it was passed to. A non-escaping closure is a closure that's called within the function it was passed into, i.e. before it returns.
$0 and $1 are closure's first and second Shorthand Argument Names (SAN for short) or implicit parameter names, if you like. The shorthand argument names are automatically provided by Swift. The first argument is referenced by $0 , the second argument is referenced by $1 , the third one by $2 , and so on.
It's a shorthand argument name.
From the Swift Book:
“Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure’s arguments by the names $0, $1, $2, and so on.”
— Apple Inc. “The Swift Programming Language.”
It helps reduce the verbosity of your code (sometimes at the cost of readability), so you don't have to write out long argument lists when defining closures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With