[swift-evolution] [Review] SE-0007 Remove C-style for-loops with conditions and incrementers

Brent Royal-Gordon brent at architechies.com
Thu Dec 10 15:35:08 CST 2015

> In this particular case you can and it won't have any noticeable side effects. But in the general case it has a different behaviour: the increment part is called on break or throw

I know there’s no single replacement that compactly implements the exact behavior of a `for` loop using a `while` loop. But we don’t usually have to mimic the full behavior:

* The vast majority of for loops don’t use an iteration variable which shadows something in the enclosing scope, so the fact that the variable isn’t scoped to the loop doesn’t usually matter.
* The vast majority of for loops don’t have iteration statements which cause side effects beyond the statement itself, so the fact that `defer` will run an extra time if you exit the loop with `break` or `throw` doesn’t usually matter.

If we provide a fix-it, we should try to make sure it doesn’t write broken code. But if that means that, sometimes, we throw up our hands and don’t offer an automatic translation, I don’t think that’s the end of the world. If you’re maintaining code with bizarre, gnarly C-style for loops with no obvious translation, you probably know how to rewrite them as while loops.

Brent Royal-Gordon

More information about the swift-evolution mailing list