[swift-evolution] repeat loop enhancement

Stephen Celis stephen.celis at gmail.com
Tue Dec 8 16:03:18 CST 2015


On Tue, Dec 8, 2015 at 4:54 PM, Jason Pollack via swift-evolution <
swift-evolution at swift.org> wrote:

> I propose the following:
>
> repeat count {
>     //Do something here
> }
>
> It's cleaner, and IMO clearer what this code is intended to do.
>

I'm not sure I like the idea of adding this functionality over "repeat". If
"for _ in" is ugly, there's always the opportunity to add a helper, e.g.:

    extension Int {
        func times(@autoclosure while condition: () -> Bool = true, body:
() -> Void) {
            // ...
        }
    }

    5.times {
        // ...
    }


> 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).
>

You can use a "where" clause to handle this in a for-in loop:

    var ok = true
    for _ in 0..<numberOfTimes where ok {
        // ...
    }

Stephen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151208/04f27383/attachment.html>


More information about the swift-evolution mailing list