Calls the given closure on each element in the sequence in the same order as a for
-in
loop.
SDK
- Xcode 9.0+
Framework
- Swift Standard Library
Declaration
func forEach(_ body: (Key) throws -> Void) rethrows
Parameters
body
A closure that takes an element of the sequence as a parameter.
Discussion
The two loops in the following example produce the same output:
let numberWords = ["one", "two", "three"]
for word in numberWords {
print(word)
}
// Prints "one"
// Prints "two"
// Prints "three"
numberWords.forEach { word in
print(word)
}
// Same as above
Using the for
method is distinct from a for
-in
loop in two important ways:
You cannot use a
break
orcontinue
statement to exit the current call of thebody
closure or skip subsequent calls.Using the
return
statement in thebody
closure will exit only from the current call tobody
, not from any outer scope, and won’t skip subsequent calls.