Calls the given closure on each element in the sequence in the same order as a for-in loop.
SDK
- Xcode 8.0+
Framework
- Swift Standard Library
Declaration
func forEach(_ body: (Element) throws -> Void) rethrows
Parameters
bodyA 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
breakorcontinuestatement to exit the current call of thebodyclosure or skip subsequent calls.Using the
returnstatement in thebodyclosure will exit only from the current call tobody, not from any outer scope, and won’t skip subsequent calls.