What does $0 represent in closures in Swift?

2019-01-18 09:15发布

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条回答
家丑人穷心不美
2楼-- · 2019-01-18 09:22

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.

查看更多
登录 后发表回答