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

Haravikk swift-evolution at haravikk.me
Sat Mar 19 19:37:58 CDT 2016


> On 19 Mar 2016, at 22:49, Charles Constant via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I'd like to see a comparison, but Python "for" loops seem more flexible to me than Swifts. It's been a couple years since I moved to Swift, but I vaguely remember a lot of cool loop stuff in Python, like "for {} else" for empty loops, etc.

Python does have a few nice features, but then that’s an argument for adding the ones we like to Swift I think. That said, the else branch for loops that don’t run is the one that stands out to me; it seems vaguely familiar like it might have been discussed already, but I don’t know what happened with it. 

Otherwise a lot of Python’s list handling is from how values are generated, which is what we already have Generators/Sequences so we can generate values however we like, though it might mean defining a new type to do it. (or push for the stdlib to add one if it’s useful enough).

Oh actually, there is one other neat feature in Python loops which is the ability to yield; essentially it just lets you resume a loop type operation where you left off, which can make methods simpler, as an example on the Python wiki here: https://wiki.python.org/moin/ForLoop <https://wiki.python.org/moin/ForLoop>
def my_range(start, end, step):
    while start <= end:
        yield start
        start += step

for x in my_range(1, 10, 0.5):
    print x
Here a function is defined to implementing a strided range, and it uses the yield command to avoid having to add extra conditionals (not sure what that actually compiles into, but I imagine it’s just hiding boilerplate you’d otherwise have to add yourself), so that’s something that might be nice too.


It’s a bit of a tangent, but at the same time it is a feature that avoids some tricky cases in Swift loops such as when you decide to break a loop but want to resume it later; both it and else blocks on loops can avoid some common boiler-plate, but they don’t necessarily do anything specifically that we can’t do. There’s also a short-hand for striding through arrays if I remember right, something like foo[:2], I don’t remember exactly, it’s been a while since I used it, but of course that’d be ambiguous with dictionaries, but other than brevity (which is arguably added learning curve) it’s no different than a .stride(2) method or whatever.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160320/362666d0/attachment.html>


More information about the swift-evolution mailing list