When to use Swift's 'for-case' loop
Assume we have the following array of tuples…
and we just want to simply filter
arthur out from the rest.
The fastest thing that comes to mind would be this:
But it would be much better if the filtering happens on the loop declaration itself, and not inside the loop body:
Now this is much cleaner as there's no
if conditional statement occupying the entire loop body, plus, you don't need to
break out of the conditional. The intent is communicated much clearly from the outset already.
But this being Swift, a succinct version is provided, and does it look beautiful!
for-case loop does away with the repeating constants and the logical AND operator that plagues
if based filtering.
So, we can use
for-case loops when filtering items from arrays.