As documented in both Array and Dictionary forEach(_:) Instance methods:
Calls the given closure on each element in the sequence<
They are more or less interchangeable, but there are two important differences.
break/continue only work in a for .. inreturn in forEach will exit the closure, but will not halt the iteration.The reason for this is that for .. in is a special form in the language (which allows break and continue to work as you expect). It is something that you can't implement in an identical way using the language itself.
However, forEach is not a special form and can be re-implemented identically by writing it as a function.
extension Sequence {
func myOwnForEach(_ body: (Self.Element) throws -> Void) rethrows {
let it = Self.makeIterator()
while let item = it.next() {
body(item)
}
}
}