[swift-evolution] repeat loop enhancement

Jason Pollack jlpollack at gmail.com
Tue Dec 8 15:54:10 CST 2015


I'd like to propose a small enhancement to the repeat loop.

Currently if we want to perform 'count' iterations in a loop, we need to do
something like:

for _ in 0 ..< count {
   //Do something here
}

It looks and feels a little awkward. We need to create an unnamed variable,
and it's easy to forget (especially for language newcomers) that the loop
starts with 0 and doesn't include count.

We can also do:

var i = 0
repeat {
    //Some code
    i += 1
} while i < 10

This is worse, in that it introduces a variable in the outer scope, and
puts the repeat count at the end. Plus, if the expression inside the repeat
is complex, the value of i may never be incremented, or may be incremented
more than once.


I propose the following:

repeat count {
    //Do something here
}

It's cleaner, and IMO clearer what this code is intended to do.

Naturally 'count' should be non-negative. A while clause is not needed,
although I could imagine it being supplied, to create a construct such as:

var ok = true
repeat numberOfTimes {
    //Do something, possibly set ok to false
} while ok

This would repeat the loop a maximum of  'numberOfTimes', but could be
ended early if some signal 'ok' is set to false (or, of course, by a break
statement).

Thoughts?

Thanks!
-Jason-
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151208/8036d0a6/attachment.html>


More information about the swift-evolution mailing list