Alexander Woodblock Alexander Woodblock - 1 year ago 133
iOS Question

Swift - avoiding nested forEach closures?

Let's say I have an array of closures that I want to run on every UITouch.
Here's the code I use:

touches.filter { touch in
return touch.phase == .Ended && touch.tapCount == 1
}.forEach { touch in
actionsOnTap.forEach { action in

It bugs me that there's nested forEach statement, and I guess there's some clean way that can be applied exactly for that case, but I can't think of it. Can anyone give me a hint?

Answer Source

This is a good example of why forEach is not a universal (or even appropriately common) replacement for for-in. This code become shorter (160 chars vs 186 chars) and clearer just using a traditional for loop:

for touch in touches {
    guard touch.phase == .Ended && touch.tapCount == 1 else { continue }

    for action in actionsOnTap {

It also doesn't create an extra array copy the way the filter does. This isn't a general reason not to use filter. filter is a very powerful tool that should be used often, but in this case, it's clearer and more efficient to use for.