Swift forEach Method

Swift forEach executes a closure once for every element in a sequence, such as an array, set, range, or dictionary. It is useful when you need to perform an operation for each element without manually managing a loop variable.

forEach is an instance method provided for types that conform to Sequence. You call it on a sequence instance and pass a closure containing the statements to execute.

Swift forEach Syntax

Following is the basic syntax for calling forEach on a sequence.

</>
Copy
sequenceInstance.forEach{ item_identifier in
    // set of instructions
    // you can use "item_identifier" identifier to access this element
}

The closure parameter named item_identifier represents the current element. The in keyword separates the closure parameters from the statements in the closure body.

Swift also supports trailing-closure syntax with a space before the opening brace, which is commonly written as follows.

</>
Copy
sequenceInstance.forEach { item in
    // Use item here
}

Swift forEach with an Array

In this example, an array of integers calls forEach. The closure receives each number in the same order in which it appears in the array.

main.swift

</>
Copy
var odds:[Int] = [3, 9, 7, 5]

odds.forEach{ odd in
    print(odd)
}

Output

3
9
7
5

When the closure contains only a short expression, you can use Swift’s shorthand argument name $0.

</>
Copy
let languages = ["Swift", "Kotlin", "Java"]

languages.forEach {
    print($0)
}

Output

Swift
Kotlin
Java

Swift forEach with an Array Index

forEach passes an element to its closure, but it does not automatically provide the element’s index. Use enumerated() when both the offset and value are required.

</>
Copy
let fruits = ["Apple", "Banana", "Mango"]

fruits.enumerated().forEach { index, fruit in
    print("\(index): \(fruit)")
}

Output

0: Apple
1: Banana
2: Mango

The value returned as index by enumerated() is a zero-based offset. For collections whose indices are not simple integer offsets, use the collection’s own indices property instead.

</>
Copy
let names = ["Asha", "Ravi", "Mina"]

names.indices.forEach { index in
    print("\(index): \(names[index])")
}

Swift forEach with a Dictionary

A Swift dictionary supplies each entry to the closure as a key-value pair. The following existing example prints the complete tuple for every entry.

main.swift

</>
Copy
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]

myDictionary.forEach{ item in
    print(item)
}

Output

(key: "Raghu", value: 82)
(key: "Mohan", value: 75)
(key: "John", value: 79)

Dictionary iteration order is not a reliable sorting mechanism. If a specific output order is required, sort the keys or entries before calling forEach.

You can destructure each dictionary entry directly into separate key and value parameters.

</>
Copy
let scores = ["Mohan": 75, "Raghu": 82, "John": 79]

scores.forEach { name, score in
    print("\(name): \(score)")
}

To print the dictionary entries in ascending key order, sort the dictionary before iterating.

</>
Copy
scores.sorted { $0.key < $1.key }.forEach { name, score in
    print("\(name): \(score)")
}

Swift forEach with a Set

A set can also call forEach. Unlike an array, a set does not preserve a fixed element order, so the printed order may differ between executions or environments.

main.swift

</>
Copy
var odds: Set = [3, 9, 7, 5]

odds.forEach{ odd in
    print(odd)
}

Output

5
7
3
9

Sort the set first when predictable output is required.

</>
Copy
let values: Set = [3, 9, 7, 5]

values.sorted().forEach {
    print($0)
}

Output

3
5
7
9

Swift forEach with a Range

Ranges conform to Sequence, so forEach can execute a closure for every value in a numeric range.

</>
Copy
(1...4).forEach { number in
    print(number * number)
}

Output

1
4
9
16

Swift forEach with Filtering

You can use a condition inside the closure when only certain elements should trigger an operation.

</>
Copy
let numbers = [2, 5, 8, 11, 14]

numbers.forEach { number in
    if number.isMultiple(of: 2) {
        print(number)
    }
}

Output

2
8
14

When the goal is to create a new collection containing matching values, use filter instead of relying on side effects inside forEach.

</>
Copy
let evenNumbers = numbers.filter { $0.isMultiple(of: 2) }
print(evenNumbers)

Output

[2, 8, 14]

Swift forEach versus for-in Loop

Both forEach and a for-in loop can process every element of a sequence, but they are not interchangeable in every situation.

  • Use forEach for a compact closure-based operation applied to every element.
  • Use for-in when you need break or continue.
  • A return statement inside a forEach closure returns from that closure invocation; it does not stop the entire sequence traversal.
  • Use map, filter, or reduce when the main purpose is to produce a transformed value rather than perform a side effect.

The following for-in loop can stop as soon as it encounters the value 3.

</>
Copy
for number in [1, 2, 3, 4, 5] {
    if number == 3 {
        break
    }

    print(number)
}

Output

1
2

The same early-exit behavior cannot be expressed with break inside a forEach closure.

Using return Inside Swift forEach

An unlabelled return inside a forEach closure skips the remaining statements for the current element. It behaves similarly to continue for that closure invocation, but it does not terminate the complete iteration.

</>
Copy
let numbers = [1, 2, 3, 4]

numbers.forEach { number in
    if number == 2 {
        return
    }

    print(number)
}

Output

1
3
4

Common Swift forEach Mistakes

  • Assuming sets or dictionaries have a fixed order: Sort the values first when ordered output is required.
  • Trying to use break or continue: Choose a for-in loop when loop-control statements are needed.
  • Using forEach to build another array: Prefer map, compactMap, or filter when creating a new collection.
  • Treating an enumerated offset as every collection’s native index: Use indices when working with a collection whose index type or indexing rules matter.
  • Expecting return to stop iteration: A return from the closure does not stop subsequent elements from being processed.

Swift forEach Frequently Asked Questions

How do I get the index in Swift forEach?

Call enumerated() before forEach to receive a zero-based offset and the corresponding element. Use the collection’s indices property when you need its actual index values.

Can I use break in a Swift forEach closure?

No. The break statement cannot be used to terminate a forEach call. Use a for-in loop when iteration must stop early.

What does return do inside Swift forEach?

It returns from the current closure invocation and processing continues with the next element. It does not return from the surrounding function or stop the remaining iterations.

Does Swift forEach preserve element order?

It visits elements in the order supplied by the sequence. Arrays have a defined order, while sets and dictionaries should not be used when a particular traversal order is required unless their elements are sorted first.

When should I use map instead of forEach in Swift?

Use map when each source element should be transformed into a value in a new array. Use forEach when the operation mainly causes a side effect, such as printing, logging, or updating external state.

Swift forEach Editorial QA Checklist

  • Confirm that array examples preserve source order and that set or dictionary examples do not promise a fixed order.
  • Verify that examples requiring early termination use for-in, not forEach.
  • Check whether an example needs a zero-based offset from enumerated() or the collection’s actual index from indices.
  • Use map, filter, or reduce when an example’s intended result is a new value or collection.
  • Ensure every displayed output matches the associated Swift code and does not imply deterministic ordering for unordered collections.

Summary of Swift forEach

Swift forEach calls a closure for every element in a sequence. It works with arrays, sets, dictionaries, ranges, and other sequence types. Use enumerated() or indices when an index is required, and prefer a for-in loop when you need break or continue.

In this Swift Tutorial, we learned how to use forEach with arrays, dictionaries, sets, ranges, indices, conditions, and closure shorthand.