forEach(_:)
Calls the given closure on each element in the sequence in the same order as a for-in loop.
Declaration
func forEach(_ body: (Self.Element) throws -> Void) rethrowsParameters
- body:
A closure that takes an element of the sequence as a parameter.
Mentioned in
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 aboveUsing the forEach 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.