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
action(touch)
}
}
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 {
action(touch)
}
}
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
.