[swift-evolution] Review for: Remove C-style for-loops with conditions and incrementers

Jacob Bandes-Storch jtbandes at gmail.com
Mon Dec 7 16:37:19 CST 2015


>
> > 2) for var i = length; --i >= 0; { ...
> >
> > This is a "count-down" loop, and isn't handled that well in Swift. The
> "guessing" translation is both wrong and fails to compile ("for i in length
> ... 0"), another attempt compiles but is easy to get wrong:
> >
> > for length.stride(to: 0, by: -1) { // wrong, includes length but not zero
> > for length.stride(through: 0, by: -1) { // wrong, still includes length
> > for (length - 1).stride(through: 0, by: -1) { // works, but people have
> switched back to Java by now
> >
> > Probably the best practice is to use reverse() on the range, since then
> you'd be using the same method on a "range literal", the indices range, or
> a collection:
> >
> > for (0 ..< length).reverse() { ...
> >
>

Have there been any ideas for addressing this in the standard library?
Perhaps a modification to Range to allow reverse intervals, or perhaps a
ReverseRange type, and a new operator ">.." which would mean the reverse of
"..<" ?

It seems "for i in ReverseCollection(a..<b)" currently works, though it
looks a little weird. Of course Nate's example "(a..<b).reverse()" works
too, but it's far too many parentheses for my taste.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151207/0f2e566b/attachment.html>


More information about the swift-evolution mailing list