- API fetch
- Array
- Async await
- Class
- Closures
- Computed property
- Concurrency
- Constants
- Data types
- Defer statement
- Dictionary
- Enum
- Escaping closure
- Extension
- For loop
- forEach
- Function
- Generics
- Guard statement
- if let statement
- Inheritance
- inout
- Lazy var
- Operator
- Optionals
- Property observers
- Property wrapper
- Protocol
- String formatting
- String interpolation
- Struct
- Switch statement
- Try catch
- Tuple
- Variables
- While loop
SWIFT
Swift forEach: Syntax, Usage, and Examples
The Swift forEach
method is a convenient way to iterate over collections like arrays, sets, or dictionaries. It allows you to execute a block of code for each element, offering clean syntax and functional style, especially when working with closures.
How to Use Swift forEach
You call forEach
on a collection and pass in a closure that defines what should happen with each element. Here's the basic structure:
let names = ["Anna", "Ben", "Carlos"]
names.forEach { name in
print("Hello, \(name)!")
}
This prints a greeting for each person in the names
array. The trailing closure receives one element at a time from the collection.
You can also use shorthand argument names:
names.forEach {
print("Welcome, \($0)!")
}
In this example, $0
refers to each element in the array during iteration.
When to Use forEach Swift
The forEach Swift
method is useful when you need to loop through every element of a collection and apply a single operation. Here are some common use cases:
1. Printing or Logging Items
You can use forEach
to print values, log user actions, or monitor behavior during debugging.
let fruits = ["Apple", "Banana", "Cherry"]
fruits.forEach { fruit in
print("Selected fruit: \(fruit)")
}
2. Performing Side Effects
If you want to perform actions like animations, network calls, or state updates for each item in a list, Swift forEach
is an expressive choice.
let scores = [78, 92, 85]
scores.forEach { score in
updateUI(for: score)
}
3. Simplifying Code
Using forEach
reduces boilerplate when working with short, concise operations inside closures. It helps make your code more readable, especially when used within SwiftUI views or reactive programming blocks.
Examples of Swift forEach
Example 1: Iterating Through an Array
let colors = ["Red", "Green", "Blue"]
colors.forEach { color in
print("Color: \(color)")
}
Example 2: Using Shorthand Closure Syntax
let pets = ["Dog", "Cat", "Rabbit"]
pets.forEach {
print("Pet: \($0)")
}
Example 3: Performing Actions on Dictionary Elements
You can iterate over dictionaries using forEach
, which receives a tuple of key and value:
let capitals = ["France": "Paris", "Japan": "Tokyo"]
capitals.forEach { country, capital in
print("\(capital) is the capital of \(country)")
}
Alternatively, access the tuple directly:
capitals.forEach { pair in
print("\(pair.value) is the capital of \(pair.key)")
}
Learn More About forEach Swift
Swift forEach vs for-in Loops
Although both forEach
and for-in
let you loop through collections, they differ in a few ways:
forEach
uses closures and does not supportbreak
orcontinue
.for-in
is more flexible and works better when you need to exit early or skip items.
let numbers = [1, 2, 3, 4, 5]
// Using for-in to break early
for number in numbers {
if number == 3 {
break // This works
}
print(number)
}
// forEach cannot do this:
numbers.forEach { number in
if number == 3 {
// break // Error: 'break' is not allowed here
}
}
If you need control flow like break
or continue
, a traditional for-in
loop is the better choice.
Using Indices in Swift forEach
Unlike a for-in
loop, forEach Swift
doesn’t give you the index of the current element directly. But you can work around this using the enumerated()
method.
let animals = ["Fox", "Wolf", "Bear"]
animals.enumerated().forEach { index, animal in
print("\(index): \(animal)")
}
This pattern is helpful when you're building UI with numbered rows or working with ordered data.
Dealing with Swift forEach Binding Error
One common issue beginners face is the Swift forEach binding error, especially when using forEach
in SwiftUI views or in non-escaping closures.
For example:
let list = ["One", "Two", "Three"]
list.forEach { item in
// Trying to modify an external @State variable might trigger a binding error in SwiftUI
}
In SwiftUI, avoid using forEach
inside views when you’re mutating state. Instead, use ForEach
(the SwiftUI view type), which is distinct from the forEach
method and supports binding properly.
Also, don’t confuse SwiftUI’s ForEach
with the array method:
// SwiftUI version
ForEach(0..<5) { index in
Text("Row \(index)")
}
If you’re working with a view and getting a binding error, make sure you’re using SwiftUI’s ForEach
, not the array method.
Nested forEach
You can nest forEach
blocks if you're working with 2D data like arrays of arrays.
let matrix = [[1, 2], [3, 4]]
matrix.forEach { row in
row.forEach { number in
print(number)
}
}
Be cautious, though. Deep nesting can make the code harder to read. In such cases, flattening or restructuring might help.
Using forEach on Sets and Ranges
The forEach
method works with any Sequence
, including sets and ranges.
let set: Set = [10, 20, 30]
set.forEach { print($0) }
(1...3).forEach { print("Step \($0)") }
Order isn't guaranteed when using sets, so avoid relying on element order during iteration.
Using forEach with Optionals and nil Values
Since forEach
is a method on sequences, you can't call it directly on an optional array. You need to safely unwrap it first.
let maybeList: [String]? = ["Earth", "Mars"]
maybeList?.forEach {
print("Planet: \($0)")
}
This will only execute if the optional has a value.
Combining forEach with map, filter, and compactMap
You can mix forEach
with other functional methods like map
, filter
, or compactMap
for expressive code.
let scores = [95, 42, 87, 100]
scores.filter { $0 >= 90 }.forEach {
print("Excellent score: \($0)")
}
This filters the list first, then prints the scores that pass the filter.
Summary
The Swift forEach
method gives you a clean and expressive way to loop through arrays, dictionaries, sets, and more. It works great for simple operations, side effects, and readability-focused code. Although it can’t break or continue like a traditional loop, it shines when used with closures and functional patterns.
To handle more complex needs like accessing the index or modifying external state, you can pair forEach Swift
with helpers like enumerated()
or opt for a for-in
loop. If you’re facing a Swift forEach binding error in SwiftUI, switch to the ForEach
view instead.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.