4

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.

nhgrif
  • 61,578
  • 25
  • 134
  • 173

4 Answers4

4

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)
}
nhgrif
  • 61,578
  • 25
  • 134
  • 173
  • 2
    Arguably, I might prefer this as `var closure = { val: Int -> Bool in return val < 10 }`, then... `while closure(x) { ... ` – nhgrif Jul 17 '15 at 00:15
  • 3
    I would much prefer `for x in 0..<10`, but I suppose the OP is experimenting with closures and how they capture variables. =) – Arkku Jul 17 '15 at 00:18
2

You need to call the closure with (), and your condition is the wrong way around so that it's false at the beginning (it should be x < 10, not x > 10). Change to:

var x = 0
var closure: () -> Bool = { x < 10 }
while closure() {
    ++x
    print(x)
}
Arkku
  • 41,011
  • 10
  • 62
  • 84
2

Two issues:

  1. Your logic is backwards. You want to print while x is less than 10, so:
  2. when you call a closure directly you do so as you would a function, i.e. with parenthesis.

Updated code, tested with Swift 2.0:

var x: Int = 0
var closure = {() -> Bool in return x < 10}
while closure() {
    x += 1
    print(x)
}
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
1

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

var x = 0
let closure = { x < 10 }
while closure() {
  x++
}
x // 10
Mundi
  • 79,884
  • 17
  • 117
  • 140