forEach(_:)
forEach(_:)
forEach(_:) Instance Method of Sequence Calls the given closure on each element in the sequence in the same order as a for-in loop.
func forEach(_ body: (Self.Element) throws -> Void) rethrowsParameters
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 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 the body closure or skip subsequent calls.
- Using the
returnstatement in thebodyclosure will exit only from
the current call to body, not from any outer scope, and won’t skip subsequent calls.