SWIFT

Swift forEach: Syntax, Usage, and Examples

The forEach method in Swift provides a clean, functional way to loop through collections like arrays, sets, and dictionaries. It's especially useful when working with closures or writing concise, readable code.


Basic Syntax

Call forEach on any collection and pass in a closure that runs for each element:

let names = ["Anna", "Ben", "Carlos"]

names.forEach { name in
    print("Hello, \(name)!")
}

You can simplify further with shorthand syntax:

names.forEach {
    print("Welcome, \($0)!")
}

Here, $0 refers to the current element in the loop.


When to Use forEach

1. Logging or Printing Values

let fruits = ["Apple", "Banana", "Cherry"]

fruits.forEach { fruit in
    print("Selected fruit: \(fruit)")
}

2. Triggering Side Effects

Use forEach to perform actions like state updates, animations, or network calls for each element:

let scores = [78, 92, 85]

scores.forEach { score in
    updateUI(for: score)
}

3. Writing Concise Code

For quick, single-line operations, forEach keeps code minimal and readable—especially in SwiftUI or reactive codebases.


Practical Examples

Iterate Through an Array

let colors = ["Red", "Green", "Blue"]

colors.forEach { color in
    print("Color: \(color)")
}

Use Shorthand Closure Syntax

let pets = ["Dog", "Cat", "Rabbit"]

pets.forEach {
    print("Pet: \($0)")
}

Loop Over Dictionary Elements

let capitals = ["France": "Paris", "Japan": "Tokyo"]

capitals.forEach { country, capital in
    print("\(capital) is the capital of \(country)")
}

Or access the tuple directly:

capitals.forEach { pair in
    print("\(pair.value) is the capital of \(pair.key)")
}

Advanced Topics

forEach vs for-in

Both forEach and for-in iterate over collections, but they differ in behavior:

  • forEach uses closures and does not allow break or continue
  • for-in supports full control flow, making it more flexible

let numbers = [1, 2, 3, 4, 5]

// Works with for-in
for number in numbers {
    if number == 3 { break }
    print(number)
}

// Won’t compile with forEach
numbers.forEach { number in
    // if number == 3 { break } // ❌ Error
}

Use for-in if you need to exit early or skip elements.


Getting the Index with forEach

forEach doesn’t expose indices by default. Use enumerated():

let animals = ["Fox", "Wolf", "Bear"]

animals.enumerated().forEach { index, animal in
    print("\(index): \(animal)")
}

Handling Binding Errors in SwiftUI

Using forEach in SwiftUI can lead to binding issues when trying to mutate state. That’s because forEach (the method) doesn’t support SwiftUI’s data flow.

Instead, use ForEach from SwiftUI:

ForEach(0..<5) { index in
    Text("Row \(index)")
}

Make sure you’re not confusing the array method with the SwiftUI view type.


Nested forEach

You can nest forEach calls for 2D data:

let matrix = [[1, 2], [3, 4]]

matrix.forEach { row in
    row.forEach { number in
        print(number)
    }
}

Avoid excessive nesting for readability.


Using forEach with Sets and Ranges

forEach works on any Sequence, including sets and ranges:

let set: Set = [10, 20, 30]
set.forEach { print($0) }

(1...3).forEach { print("Step \($0)") }

Sets don’t preserve order, so don’t rely on sequence.


forEach on Optional Collections

Unwrap optionals before calling forEach:

let maybeList: [String]? = ["Earth", "Mars"]

maybeList?.forEach {
    print("Planet: \($0)")
}

This prevents crashes and keeps your code safe.


Combining with map, filter, and compactMap

You can chain functional methods with forEach for powerful, readable logic:

let scores = [95, 42, 87, 100]

scores.filter { $0 >= 90 }.forEach {
    print("Excellent score: \($0)")
}

This filters first, then performs an action on matching values.


Summary

forEach gives you a clean, expressive way to loop over collections in Swift. It’s perfect for simple, one-off operations, especially when working with closures, SwiftUI, or functional code.

While it lacks control flow tools like break or continue, you can combine it with enumerated(), filter, or map for more advanced behavior. For UI updates or value transformations, forEach keeps your code elegant and concise.

When working in SwiftUI, use ForEach for rendering views, not the array method. Understanding the difference helps avoid common errors and improves code clarity.

Learn to Code in Swift for Free
Start learning now
button icon
To advance beyond this tutorial and learn Swift by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH

Reach your coding goals faster