xcode $0 在 Swift 的闭包中代表什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27491620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:22:13  来源:igfitidea点击:

What does $0 represent in closures in Swift?

iosxcodeswiftclosures

提问by lostAtSeaJoshua

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?

我看到 swift 中的闭包里面有 $0,有时他们使用 $1。到底什么是 $0,还有什么是你可以使用的 $x?

Here are examples of it in use.

以下是它的使用示例。

applyMutliplication(2, {##代码## * 3})
array.map({##代码## + 1})

Thanks!

谢谢!

采纳答案by Andy Obusek

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

“Swift 自动为内联闭包提供速记参数名称,可用于通过名称 $0、$1、$2 等引用闭包参数的值。”

— Apple Inc. “Swift 编程语言”。

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.

它有助于减少代码的冗长(有时以可读性为代价),因此您不必在定义闭包时写出很长的参数列表。