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

Michel Fortin michel.fortin at michelf.ca
Sat Dec 12 13:48:58 CST 2015

Le 12 déc. 2015 à 13:42, Rainer Brockerhoff <rainer at brockerhoff.net> a écrit :

> Yikes. This is why I dislike the C-stye for loop; I never remember such
> details properly, and avoid putting multiple items in there. (Same goes
> for function pointer syntax and ObjC block pointer syntax, nested
> typedefs, etc.)
> Offhand (can't test right now) I suppose that means there's no use in
> adding `repeat` (or, `loop`, or whatever) to `for ... in`?
> Would you say it'd still be useful for the `while` loop?

I don't think it's particularly intuitive that the two consecutive blocks separated by a keyword are part of the same loop body in the first place. Somebody is prone to do the same mistake you did with a while loop, although maybe it's less likely (I don't really know).

It'd certainly be useful if the C-style for loop disappear to have a decent way to express it using a while loop, but I'm not sure this is the way to go. As things stand, we have the following ideas about augmenting a while loop (with various keywords I won't enumerate):

	while condition() next increment() {

	while condition() {
	} repeat {

Perhaps we could consider adding something like `defer` but that would not execute on `break` or `throw`:

	while condition() {
		reloop { increment() }

Or maybe just make the whole C-style for loop a special kind of while loop by replacing semicolons with keywords:

	for var i = 0 while condition() next increment() {

There's so many ideas floating around, but it doesn't seem like any of them is getting much traction right now.

My personal preference goes to this last one that essentially keeps the C-style for loop but with keywords. It's easily recognizable to those who already know the C-style for loop, easier to understand to those who don't, and it does not force all C-style for loops to be rewritten using a different control flow.

Moreover, if you accompany this change with a fix-it having a special case that migrates the old forms "for;;" and "for(;;)" by proposing the appropriate range-based for-in loop as a replacement for simple forward iteration over integers, beginners writing "for;;" will likely switch to using the for-in form after being shown the way once or twice.

Michel Fortin
michel.fortin at michelf.ca

More information about the swift-evolution mailing list