[swift-evolution] [Pitch] Retiring `where` from for-in loops

Erica Sadun erica at ericasadun.com
Wed Jun 8 22:51:14 CDT 2016

> On Jun 8, 2016, at 9:36 PM, Brent Royal-Gordon <brent at architechies.com> wrote:
>> Upon accepting SE-0099, the core team is removing `where` clauses from condition clauses, writing "the 'where' keyword can be retired from its purpose as a boolean condition introducer." 
>> Inspiried by Xiaodi Wu, I now propose removing `where` clauses from `for in` loops, where they are better expressed (and read) as guard conditions. 
> Do you propose to remove `for case` as well? That can equally be handled by a `guard case` in the loop body.
> Alternate proposal: Move `where` clauses to be adjacent to the pattern—rather than the sequence expression—in a `for` loop, just as they are in these other syntaxes.
> 	for n where n.isOdd in 1...1_000 { … }
> This makes them more consistent with the syntax in `switch` cases and `catch` statements, while also IMHO clarifying the role of the `where` clause as a filter on the elements seen by the loop.

I saw your post on that *after* I finished sending this. Moving `where` next to the pattern, like you'd find in `catch` and switch `case`, the code would look like this:

for i where i % 2 == 0 in sequence {
    // do stuff

I agree that's really clever and an improvement but after coming up with all the points about wrong expectations about termination vs filtering, the better use of guard, and fetishes about vertical compactness, I think (call it +0.6) I'm going to stick to my guns on this one - and for `for case` too. I've been wuxxed.

* New users might expect the sequence to terminate as soon as i % 2 is 1, rather than the correct interpretation which is "this is a filtering operation"
* The code can be expressed less ambiguously as 

for i in sequence.filter({ return i % 2 == 0 }) {
    // do stuff

* The while version can be expressed as

for i in sequence.prefix(while: { return $0 % 2 == 0 } ) {
    // do stuff

* The code can also use `guard` statements as needed with `break` and `continue`

(And yes, I should have pointed out filter and prefix as well as guard in my first email)

-- E

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160608/d6894a75/attachment.html>

More information about the swift-evolution mailing list