When to use forEach(_:) instead of for in?

Viewed 19406

As documented in both Array and Dictionary forEach(_:) Instance methods:

Calls the given closure on each element in the sequence in the same order as a for-in loop.

Nevertheless, adapted from Sequence Overview:

A sequence is a list of values that you can step through one at a time. The most common way to iterate over the elements of a sequence is to use a for-in loop.

Implying that iterating sequence by forEach(_:) or for in:

let closedRange = 1...3

for element in closedRange { print(element) } // 1 2 3

closedRange.forEach { print($0) } // 1 2 3

Or (Array):

let array = [1, 2, 3]

for element in array { print(element) } // 1 2 3

array.forEach { print($0) } // 1 2 3

Would gives the same output.

Why forEach(_:) even exist? i.e what is the benefit of using it instead of the for in loop? would they be the same from performance point view?

As an assumption, it could be a syntactic sugar especially when working with functional programming.

4 Answers

I recently ran across a use case where using forEachwas preferable in a tangible way to for in. Let's say you want to remove all sublayers from a layer. A statement such as the below doesn't work as you need to unwrap the [CALayer]

for layer in self.videoContainerView.layer.sublayers!

If sublayers are nil, you will get a crash. This forces you to check to see if there are sublayers first. However, a forEach makes this much simpler as in the following:

self.videoContainerView.layer.sublayers?.forEach { $0.removeFromSuperlayer() }

In addition to above answers one more reason that differentiates for loop from forEach is that with for loop we can also chose to implement that logic using where based pattern matching instead, like

for adBanner in adBanners where !adBanner.isLoading {

The above kind of control flow related features are what makes for loops so powerful, but if we don’t need that level of control, using a call to forEach might give us slightly simpler-looking code.

So in short using a for loop gives us a much greater degree of control over an iteration

Related