[swift-evolution] Add a while clause to for loops

Brent Royal-Gordon brent at architechies.com
Wed Jun 8 22:23:18 CDT 2016

> This reads to me as “repeat the following block until this fails to be true”, the conditional binding in this case fails to be true if someCondition(value) isn’t true, so the loop ends. I think the key thing here is that the where clause is for the conditional binding and not the loop itself, so in this respect it behaves exactly like an if or guard statement. Meanwhile:
> 	for eachValue in theValues where someCondition(eachValue) { … }
> Reads as “for everything in theValues do the following if someCondition(eachValue) is also true”, in other words this loop always tries to visit every element of the sequence (a while loop has no implicit awareness of the sequence, it’s really just an if statement that runs over and over). In this case the where clause is part of the loop itself. There may be an argument that where should be renamed on for loops to better distinguish this, but once you consider that there’s no pattern or conditional binding here I think it makes a reasonable amount of sense.

The original sin here was in connecting the `where` clause to the for loop's sequence expression, rather than its pattern. If `where` were positioned right after the loop variable:

	for eachValue where someCondition(eachValue) in theValues { … }

It would be much clearer that `where` constrains the values seen by the loop body.

I'm not sure why the `where` clause was placed where it is. I suspect it has something to do with the `where` clause potentially being more complex than the sequence expression, but I was not in the room where it happened, so that's idle speculation.

Brent Royal-Gordon

More information about the swift-evolution mailing list