What does $0 represent in closures in Swift?

只谈情不闲聊 提交于 2019-12-17 19:06:50

问题


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.



来源:https://stackoverflow.com/questions/27491620/what-does-0-represent-in-closures-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!