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

Haravikk swift-evolution at haravikk.me
Fri Jun 10 15:17:29 CDT 2016

> On 10 Jun 2016, at 20:45, Xiaodi Wu <xiaodi.wu at gmail.com> wrote:
> I'm sorry, but until this discussion I had never heard of a coding style that advocates for conservation of vertical space. There's a lot of argument whether 80 characters is still a relevant line length, but I've never heard discussion that a single long line is better than multiple lines as a general principle.

We’re not talking about a single super long line here, my actual uses of for in where don’t get much longer than the examples I’ve given, besides which the where keyword itself does a good job of breaking up the line into distinct pieces. Compared to say a long line full of chained .filter and .map or whatever it’s very clean.

At no point am I advocating shoving everything onto one line just for the sake of it, however, without a where clause a for in loop’s opening line tends to be very short so it leaves a nice chunk of extra space that’s ideal for a simple condition. Anything longer can, and absolutely should, span multiple lines in whatever form the developer prefers, no-one is suggesting that where clauses should remain in so we can ruin our code by shoving as much as possible on one line.

Regarding some of the numbers that have come up about for in vs for in where loops (in my own code I’m close to maybe of 20% of my for in loops using it), it’s important to recognise that the use of the where clause isn’t well advertised. When I started out with Swift I only knew that it could be used on cases in a switch statement, and later that it was used with complicated generics. It wasn’t until I joined the mailing list that I found out it could be used with conditional bindings and loops, but when I did I started using it almost immediately.

Plus a lot of developers are coming from other languages where nothing like this existed, so if they don’t discover it somewhere it’s not surprising if they don’t use it. Also, the important figures aren’t actually for in versus for in where, what’s needed is a count of for in where versus loops that use either if/guard continue (not break) or .filter() (i.e- only loops that could use a where clause but don’t). Most for in loops visit every element so it’s not surprising that they outnumber for in where by a large margin. I use it quite a bit in place of .filter(), and I’d use this form even more if there were a breaking alternative, I probably wouldn’t use a combined filtering and breaking version much though, but I wouldn’t be opposed to the possibility.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160610/c39d9e3d/attachment.html>

More information about the swift-evolution mailing list