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]) }
                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 the n-th element of your thenums array.
So the first time contains
1, then2and so on...
Here's the output
1
2
3
4
forEach with the for-in constructSo 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.
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.
forEach a closure that accept a single param in input where the param has the same type of the ArrayforEach will apply that closure to each element of the array.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)
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With