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.

+3


source to share


4 answers


Two questions:

  • Your logic is reversed. You want to print rather x

    less 10

    , 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)
}

      

+2


source


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

      

+4


source


You need to call the closure with ()

and your condition will be wrong, so it's false

at the start (it should be x < 10

, not x > 10

). Change to:

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

      

+2


source


Take advantage of shortening to make your code more concise and elegant.

var x = 0
let closure = { x < 10 }
while closure() {
  x++
}
x // 10

      

+1


source







All Articles