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.
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.
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
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.
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.
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.
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
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.
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.
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
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.
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.
(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.
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.
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
forEachfor a compact closure-based operation applied to every element. - Use
for-inwhen you needbreakorcontinue. - A
returnstatement inside aforEachclosure returns from that closure invocation; it does not stop the entire sequence traversal. - Use
map,filter, orreducewhen 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.
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.
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-inloop when loop-control statements are needed. - Using forEach to build another array: Prefer
map,compactMap, orfilterwhen creating a new collection. - Treating an enumerated offset as every collection’s native index: Use
indiceswhen 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, notforEach. - Check whether an example needs a zero-based offset from
enumerated()or the collection’s actual index fromindices. - Use
map,filter, orreducewhen 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.
TutorialKart.com