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.
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.
var x = 0
var closure = { () -> Bool in return x < 10 }
while closure() {
++x
print(x)
}
var x = 0
var closure = { () -> Bool in return x < 10 }
while closure() {
++x
println(x)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With