Swift:$ 0如何在Array.forEach中工作? [英] Swift : How $0 works in Array.forEach?
问题描述
$ p $
@IBOutlet var headingLabels:[UILabel]!
....
headingLabels.forEach {$ 0.attributedText = NSAttributedString(string:$ 0.text !, attributes:[NSKernAttributeName:1])}
$ c
$ b 解决方案
简短的回答
此代码
let nums = [1,2,3,4]
nums.forEach {print($ 0) }
在 forEach
>
我的意思是这部分 {print($ 0)}
被执行4次(对于数组内的每个元素都执行一次)。每次执行 $ 0
都包含您的第n
元素的副本 nums
数组。
所以第一次包含 1
,然后 2
等等...
以下是输出:
1
2
3
4
比较 forEach
与 for-在
构建
所以我们可以说 $ 0
就像
$ pre $ n code $ n $ {
print $ (n)
}
是的,它的含义几乎相同。
它是如何工作的?
forEach
方法接受关闭。关闭有这个签名。
(Self.Generator.Element)throws - >无效
使用 forEach
与您签订合同。
- 您向
forEach
在输入中接受一个参数,其中param具有相同类型的数组 -
forEach
会将该闭包应用于
示例
nums.forEach {(n)in
print(n)
}
然而,在Swift中,可以省略闭包参数的显式名称。在这个闭包内部,你可以使用
$ 0
作为第一个参数,第二个参数是$ 1
所以前面的代码片段也可以写成如下
nums.forEach {
print($ 0)
}
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]) }
解决方案Short answer
Look at this code
let nums = [1,2,3,4] nums.forEach { print($0) }
Here the closure following
forEach
I mean this part
{ print($0) }
is executed 4 times (once for every element inside the array). Each time it is executed
$0
contains a copy of then-th
element of your thenums
array.So the first time contains
1
, then2
and so on...Here's the output
1 2 3 4
Comparing
forEach
with thefor-in
constructSo can we say tha
$0
is like then
value in the following code?for n in nums { print(n) }
Yes, it has pretty much the same meaning.
How does it work?
The
forEach
method accept a closure. The closure has this signature.(Self.Generator.Element) throws -> Void
When you use the
forEach
it makes a "contract" with you.- 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.
Example
nums.forEach { (n) in print(n) }
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屋!
- You provide to the