Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Closure as a While Loop's Condition

I want to use a closure as a condition for a while loop. This is what I have:

var x: Int = 0
var closure = {() -> Bool in return x > 10}
while closure {
    x += 1
    println(x) // never prints
}

It never prints anything. If I change it to closure(), it doesn't work either.

Any help would be appreciated.

like image 812
DefinitelyNotAPlesiosaur Avatar asked Jan 08 '23 23:01

DefinitelyNotAPlesiosaur


1 Answers

There are two problems here.

Firstly, as written, your code won't even compile. You need to change while closure to while closure().

Second, the bigger problem, your closure logic is wrong. x > 10 never returns true because x is never greater than 10. Flip the sign over and it'll work.

Swift 2

var x = 0
var closure = { () -> Bool in return x < 10 }
while closure() {
    ++x
    print(x)
}

Swift 1.2

var x = 0
var closure = { () -> Bool in return x < 10 }
while closure() {
    ++x
    println(x)
}
like image 52
nhgrif Avatar answered Feb 07 '23 06:02

nhgrif