简体   繁体   English

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

[英]What does $0 represent in closures in Swift?

I have seen closures in Swift use $0 internally and sometimes they use $1 .我见过 Swift 中的闭包在内部使用$0 ,有时他们使用$1 What exactly is $0 and what are other $X can you use?到底什么是$0 ,您还可以使用哪些其他$X

Here are examples of it in use:以下是它的使用示例:

applyMutliplication(2, {$0 * 3})
array.map({$0 + 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.” “Swift 自动为内联闭包提供速记参数名称,可用于通过名称 $0、$1、$2 等引用闭包参数的值。”

— Apple Inc. “The Swift Programming Language.” — 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.它有助于减少代码的冗长(有时以可读性为代价),因此在定义闭包时不必写出长参数列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM