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

Michel Fortin michel.fortin at michelf.ca
Wed Dec 9 09:15:43 CST 2015


> Le 9 déc. 2015 à 2:04, Greg Parker via swift-evolution <swift-evolution at swift.org> a écrit :
> 
> 
>> On Dec 7, 2015, at 5:29 PM, Kevin Ballard via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> var i = initial
>> while cond(i) {
>>   defer { i = increment(i) }
> 
> Strange. Can the compiler optimizer handle that efficiently?
> 
> 
>> Michel Fortin wrote:
>> 
>> var i = 0
>> var first = true
>> while ({ () -> Bool in if first { first = false } else { i = increment(i) }; return cond(i) }()) {
>> }
> 
> I fear that teaching the C-style for loop is easier than teaching that.

True. But if the C-style for loop was not part of the language, would you feel obligated to teach an equivalent like the above?

Here's another idea though. We could have a while loop that looks like this:

	var i = 0
	while i < 5 reloop i += 1 {
	}

The reloop part would be executed upon reaching the end of the loop block, or whenever a continue is encountered: always just before reevaluating the condition. Unlike defer, the reloop part does not execute on break, return or throw.

It works just like a C-style for loop, minus the oddity regarding the scope of the loop variable.


-- 
Michel Fortin
michel.fortin at michelf.ca
https://michelf.ca



More information about the swift-evolution mailing list