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

Brandon Knope bknope at me.com
Thu Jun 23 21:55:26 CDT 2016

Maybe something like this?

let calendar = Calendar.current()

for date in dates where calendar.isDateInToday(date) {
    //process date only in today


for date in dates {
    guard calendar.isDateInToday(date) else { continue }

The where keeps the body of the for loop uncluttered so it can focus *just* on what's important: processing dates that are only in a certain day.

Also, let's pretend someone comes along later and decides to add some code to this loop:

for date in dates {
    /** Anything here is using an untested date **/
    /** Some programmer comes along later and adds unrelated 
       * date handling code...or mistakenly adds code here **/

    guard calendar.isDateInToday(date) else { continue }

The where tells that this loop was intended to only deal with certain dates and enforces it. Guard only guards against it if code is added after it.

With the where clause it is:
- self-documenting
- must be changed if you want a different behavior, preventing unintended mistakes later

I don't want to say this is a "more" challenging example of filtering, but I do think it can show its expressiveness.


Sent from my iPad

> On Jun 23, 2016, at 10:14 PM, Erica Sadun via swift-evolution <swift-evolution at swift.org> wrote:
>> On Jun 23, 2016, at 7:34 PM, William Shipley via swift-evolution <swift-evolution at swift.org> wrote:
>> 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 have used odd-even examples a lot when presenting this concept, and inevitably the response
> is "Whoa, that's cool". What I'm missing are more challenging real-world use-cases to justify 
> the construct, and an exploration of why the challenging cases would not need debugger 
> support at that point.
> My concern (and I am happy to be corrected) is that any code that becomes slightly more 
> complex loses the beauty and readability and hinders debugging at the same time.
> -- E
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160623/0c0bfcea/attachment-0001.html>

More information about the swift-evolution mailing list