Using closure as a loop condition
I want to use 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
}
He never prints anything. If I change it to closure()
, it doesn't work either.
Any help would be appreciated.
source to share
Two questions:
- Your logic is reversed. You want to print rather
x
less10
, so: - when you call the closure directly, you do it as if you were executing a function, that is, with parentheses.
Updated code tested with Swift 2.0:
var x: Int = 0
var closure = {() -> Bool in return x < 10}
while closure() {
x += 1
print(x)
}
source to share
There are two problems here.
First, as written, your code won't even compile. You need to change while closure
to while closure()
.
Second, the big problem, the logic closure
is wrong. x > 10
never returns true
because x
never again 10
. Flip the sign and it will 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)
}
source to share