[swift-evolution] A (better) Swift Equivalent For The Classical For-Loop With Numeric Scalars

Jeremy Pereira jeremy.j.pereira at googlemail.com
Tue Mar 29 04:07:29 CDT 2016


> On 23 Mar 2016, at 15:50, Haravikk <swift-evolution at haravikk.me> wrote:
> 
>> 
>> 
>> True, but we could have argued the same about the `where` keyword and that is in existence. :-)
> 
> Speaking of where, why wouldn’t you just do:
> 
> 	for eachElement in theIntegerSequence where eachElement < 5 { … }

Apologies, I’m a bit late to the party here, but I’ve been away on holiday.

The problem with `where` is that the loop still consumes all the elements in the sequence even in the case where the where clause can never be true again. So the above is the same as

    for eachElement in theIntegerSequence
    {
        if eachElement < 5 { … }
    }

I think a more useful construct is one that is equivalent to

    for eachElement in theIntegerSequence
    {
        guard eachElement < 5 else { break }
        ...
    }

but as Brent pointed out, putting that guard statement at the top of the loop body pretty much answers my main criticism of not having something like for … while …



> 
> I think simplified striding is really all we need to cover c-style loop replacement, the only case that can’t be covered is one that uses some kind of variable stride amount, i.e- replacing:
> 
> 	var step = 0
> 	for (var i = 0; i < 100; i += step) { step += 1 }
> 
> But I think that’s unusual enough that it doesn’t really matter.

And it is covered by using a while loop. 

It makes me smile somewhat that people think Swift is unusual not having a C style for loop. When I learned C, it was the _only_ language with such a flexible for loop. All of the others (at least those that I came in contact with) only had the simple for i = x to y step z style for loop. 



More information about the swift-evolution mailing list