Swift:$0 在 Array.forEach 中是如何工作的? [英] Swift : How $0 works in Array.forEach?
问题描述
我已经看到大多数 swift 开发人员开始使用 .forEach,了解它的另一种迭代数组的方法.但是$0"的含义是什么以及它是如何工作的?如果它是一个索引,那么它应该增加 0,1,2...
I have seen most of the swift developer are starting using .forEach, understood its another way to iterate array. But what is the meaning of '$0' and how it works? If it's an index then it should increment 0,1,2...
@IBOutlet var headingLabels: [UILabel]!
....
headingLabels.forEach { $0.attributedText = NSAttributedString(string: $0.text!, attributes: [NSKernAttributeName: 1]) }
推荐答案
简短回答
看看这段代码
let nums = [1,2,3,4]
nums.forEach { print($0) }
这里是forEach
我的意思是这部分 { print($0) }
执行 4 次(对数组中的每个元素执行一次).每次执行时,$0
都包含 nums
数组的 n-th
元素的副本.
is executed 4 times (once for every element inside the array). Each time it is executed $0
contains a copy of the n-th
element of your thenums
array.
所以第一次包含1
,然后是2
,依此类推...
So the first time contains
1
, then2
and so on...
这是输出
1
2
3
4
比较 forEach
与 for-in
结构
那么我们可以说 $0
就像下面代码中的 n
值吗?
Comparing forEach
with the for-in
construct
So can we say tha $0
is like the n
value in the following code?
for n in nums {
print(n)
}
是的,它的含义几乎相同.
Yes, it has pretty much the same meaning.
forEach
方法接受一个闭包.闭包有这个签名.
The forEach
method accept a closure. The closure has this signature.
(Self.Generator.Element) throws -> Void
当您使用 forEach
时,它会与您签订合同".
When you use the forEach
it makes a "contract" with you.
- 您向
forEach
提供一个闭包,该闭包接受输入中的单个参数,其中该参数具有与数组相同的类型 forEach
会将该闭包应用于数组的每个元素.
- You provide to the
forEach
a closure that accept a single param in input where the param has the same type of the Array - The
forEach
will apply that closure to each element of the array.
示例
nums.forEach { (n) in
print(n)
}
但是在 Swift 中,您可以省略闭包参数的显式名称.在这个闭包里面,你可以使用 $0
作为第一个参数,$1
作为第二个参数,以此类推.
However in Swift you can omit explicit names for the parameters of a closure. In this inside the closure you can refer that params using $0
for the first param, $1
for the second one and so on.
所以前面的代码片段也可以写成下面这样
So the previous snippet of code can be also be written like below
nums.forEach {
print($0)
}
这篇关于Swift:$0 在 Array.forEach 中是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!