[swift-evolution] SE-0105: Removing Where Clauses from For-In Loops

William Shipley wjs at mac.com
Thu Jun 23 20:34:48 CDT 2016


I’m against removing “where" from “for/in”. I use it in my code and I think it aids readability quite a bit. In the example:

for x in theArray where x % 2 == 1 { print (x) }
I think it’s artificially confusing because the print is on the same line. If we break the line we see the “where” at the end of the line and it reads like the English I would use to tell someone what this loop is doing:

for x in theArray where x % 2 == 1 {
... 
To me this reads very clearly: I’m looping through some values BUT I want to skip some, now here’s what I’m going to do with these values. Using “guard” for this purpose adds unnecessary lines of code and also allows for the (common in my experience!) bug of accidentally using “break” or “return” inside the guard instead of “continue”. Also, guard / continue just doesn’t read like a filter.

Having the filtering/where logic (eg: what I’m _iterating_ over) separated from the body of the loop (eg: what i’m _doing_ to those objects) is one of my favorite things about Swift.

Yes, we could also do that with “filter” followed by “forEach”, but then it would read totally backwards and I don’t always want that. (I mean, at this point “for/in blah” could be considered syntactic sugar for "blah.forEach {}” but I still want "for/in".)


for x in theArray where x % 2 == 1 { print (x) }
while let x = anArray.popLast() where x % 2 == 1 { print(x) }
In this example case the “while” is only unclear to me because Swift has the odd thing where it does pattern matching using “let” as well as using let in a plain old assignment, and it’s hard to know which is which. I could argue that it’s also unclear why I can’t type “let x = anArray popLast where x % 2 == 1” by itself on a line and have x be an optional. (I would have liked it if we used “match” as a keyword instead of “let” when we’re doing patterns, but there you go.)

-Wil
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160623/26db1614/attachment.html>


More information about the swift-evolution mailing list