What does $0 represent in closures in Swift?

2019-01-18 09:29发布

问题:

I have seen closures in swift have $0 inside of it 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})

Thanks!

回答1:

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.