Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift : How $0 works in Array.forEach?

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]) }
like image 490
SaRaVaNaN DM Avatar asked Jul 14 '16 13:07

SaRaVaNaN DM


1 Answers

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 the n-th element of your thenums array.

So the first time contains 1, then 2 and so on...

Here's the output

1
2
3
4

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.

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.

  1. You provide to the forEach a closure that accept a single param in input where the param has the same type of the Array
  2. 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)
}
like image 73
Luca Angeletti Avatar answered Oct 16 '22 02:10

Luca Angeletti