[swift-evolution] Extending declaration scope to condition for `repeat { } while ()`

Erica Sadun erica at ericasadun.com
Mon Jul 18 19:31:28 CDT 2016


A few quick points. Apologies for the brevity.

1. Please take a look at the stateful version of `sequence`
2. Additive, non-breaking proposals should be deferred until next month.

In regard to point 1, create a sequence that terminates on false. 
So you can hack something up like this (of course, hopefully a little more elegant)

extension Bool {
    var optionalPresentation: Bool? { return self ? self : nil }
}

// a fake example of terminating check
func doSomething() -> Bool {
    return arc4random_uniform(10) < 9 // 10% chance of ending
}

for nextItem in Swift.sequence(
    state: doSomething().optionalPresentation,
    next: { _ in return doSomething().optionalPresentation }) {
        
        // use nextItem state here
        // body of loop
}

Best,

-- E


> On Jul 18, 2016, at 11:52 AM, Braeden Profile via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Good morning, Swift community!
> 
> I’ve come across a situation a number of times where I write code that has to try something one or more times using a `repeat…while` loop and the condition relies upon variables that should be declared within the scope of the loop.
> 
> repeat
> {
> 	let success = doSomething()
> }
> while !success
> 
> The compiler unnecessarily prohibits this:  “Use of unresolved identifier four.”  In this simple case, we can write:
> 
> repeat
> { }
> while !doSomething()
> 
> But in a more complex situation, we are forced to write:
> 
> var success: Bool
> repeat
> {
> 	success = doSomething()
> }
> while !success
> 
> 
> We could change this so that the declarations within the top level scope of the loop are accessible from the condition.
> 
> Thanks for reading my first post to the Swift discussion board!
> —Braeden
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160718/30903f26/attachment.html>


More information about the swift-evolution mailing list