[swift-evolution] Remove forEach?

Chris Eidhof chris at eidhof.nl
Tue Dec 8 13:07:53 CST 2015


Hi all,

As long as the `for` loop is in the language, I don’t really see the use of `forEach`. I understand that it can read much nicer to write something like `a.map { something }.filter { somethingElse }.forEach {` rather than a `for` loop. However, I think the costs don’t outweigh the benefits. It might look like a for loop can just be replaced by a `forEach`, however, this is not true in the general case. For example, consider the following example:

    func indexOf_foreach(element: Element) -> Int? {
        self.indices.filter { idx in self[idx] == element }.forEach { idx in
            return idx
        }
        return nil
    }

The code above (I realise it’s quite inefficient) might look like it’s returning the first index for which the filter’s condition returned true. However, the first occurrence of return is actually returning inside the closure, not the outer function. So the result of this function is always nil.

Another solution would be to give a good warning/error message here (you’re trying to return an Optional value where we expect a ()). However, this is also problematic when dealing with side-effects. For example:

[1,2,3,4,5].forEach { num in
   print(num)
   if num > 3 { return }
}

I think it’s quite easy to get things wrong with forEach, so I’d propose removing it and rather having a regular for loop. (Erica-style).

Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151208/372d79ed/attachment.html>


More information about the swift-evolution mailing list