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

Xiaodi Wu xiaodi.wu at gmail.com
Wed Jun 8 22:38:31 CDT 2016


That's a good insight, Brent. That placement of where is actually pretty
ingenious and probably unambiguous.
On Wed, Jun 8, 2016 at 22:23 Brent Royal-Gordon <brent at architechies.com>
wrote:

> > 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
> Architechies
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160609/8d50f2cd/attachment.html>


More information about the swift-evolution mailing list