Deciding between a for loop or forEach in swift
Published on: April 23, 2024Swift offers multiple ways to iterate over a collection of items. In this post we’ll compare a normal for loop to calling forEach
on a collection.
Both for x in collection
and collection.forEach { x in }
allow you to iterate over elements in a collection called collection
. But what are their differences? Does one outperform the other? Is one better than the other? We’ll find out in this post.
Using a regular for loop
I’ve written about for loops in Swift before so if you want an in-depth look, take a look at this post.
A regular for loop looks as follows:
for item in list {
// use item
}
Unless we break out of our for loop with either a break
or a return
statement, the loop will iterate all elements in our list without interruption. For loops in Swift allow us to use the continue
keyword to cut a specific iteration short and moving on to the next element.
Using forEach to iterate elements
If we use a forEach
to iterate a collection of items, we can write code as follows:
list.forEach { item
// use item
}
While for loops are a language construct, forEach
is a function defined on collections. This function takes a closure that will be called for every element in the collection.
If we want to abort our iteration, we can only return
from our forEach
closure which is an equivalent to using continue
in our classic for loop. Returning from a forEach
does not end the loop, it just aborts the current iteration.
Making a decision
A forEach
is mostly convenient when you’re chaining together functions like map
, flatMap
, filter
, etc. and you want to run a closure for literally every element in your list.
In almost every other case I would recommend using a plain for loop over a forEach
due to being able to break out of the loop if needed, and also I prefer the readability of a for loop over a forEach
.
Performance-wise the two mechanisms are similar if you want to iterate over all elements. However, as soon as you want to break out of the loop early, the plain for loop and its break
keyword beat the forEach
.