Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does $0 represent in closures in Swift?

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}) 
like image 278
lostAtSeaJoshua Avatar asked Dec 15 '14 19:12

lostAtSeaJoshua


People also ask

What does .0 mean in Swift?

So the . 0 means the first or zeroth element of the tuple and . 1 means the second element.

What is a closure expression in Swift?

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 .

What are the types of closures in Swift?

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.

How do you use $0 and $1 in Swift?

$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.


1 Answers

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.

like image 107
Andy Obusek Avatar answered Oct 04 '22 03:10

Andy Obusek