[swift-evolution] Feature proposal: Range operator with step

Hans Huck gutgedacht at gmx.de
Fri Apr 15 16:59:44 CDT 2016


Brent Royal-Gordon via swift-evolution <swift-evolution at ...> writes:
> 
> > for i in p1..<p2 by x
> > 
> > as syntactic sugar for and internally mapped to
> > 
> > for i in (p1..<p2).striding(by: x)
> > 
> > Best of both worlds?
> 
> Look. It is very, very unlikely that you will get people to add syntactic
> sugar *just* for striding and *just* for the for loop. If this:
> 
> 	for i in (1..<10).striding(by: 2) { … }
> 
> Is so ugly that we need special syntactic sugar for it, then so is this:
> 
> 	(1..<10).striding(by: 2).map { … }
> 

It's unnecessarily unwieldy, and I'd prefer `.by(x)`, `.step(x)`, or even
`.stride(x)` over `.striding(by: x)` any day. I understand potential
reservations towards "by", even though I don't share them, but these cannot
possibly apply to "step" or "stride".

> That means we would need an expression along the lines of:
> 
> 	1..<10 by 2
> 
> Which could be used anywhere.
>

That's where I disagree. You see, what I'm trying to achieve here is not to
fight tooth and claw for an ever shorter step syntax in collections.

I just want to *get rid of an anomaly*, which imo justifies a new keyword
for a (heavily utilized) special case.

So far, you can fully use all core control structures in Swift without
resorting to methods/protocols, let alone noisy ones. While, While-Repeat,
If-Else, Switch, and (plain) For-In all work in a straight forward,
imperative, expected way, and that's highly desirable, because it's
intuitive and comes free of cognitive load.

But by removing (which btw I fully support) the C-style For-loop from the
language, suddenly one of the simplest and most primal tasks stands out
unpleasantly:

Counting from x to y with a step size of z -- which is the very application
the For-loop originally was created for.

Would you like to be forced to work with a While-loop like the one below?

while i.loop(initialize: 1, conditionlessorequal: 10, increaseby: 3)
 
Yeah, me neither ;)

Again: I'm not aiming at collection syntax in general; it just gets in the
line of fire, because the only remaining For-loop in Swift currently doesn't
know how to step through a sequence of numbers without making a fuss. 

-- Hans



More information about the swift-evolution mailing list