Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @autoclosure parameter in async block in Swift?

Tags:

closures

swift

I would like to call an @autoclosure parameter inside dispatch_async block.

func myFunc(@autoclosure condition: () -> Bool) {
  dispatch_async(dispatch_get_main_queue()) {
    if condition() {
      println("Condition is true")
    }
  }
}

I get the following error.

Closure use of @noescape parameter may allow it to escape.

Is it possible to call @autoclosure parameter asynchronously?

Tested in Xcode 6.4 (6E23).

like image 703
Evgenii Avatar asked Dec 11 '22 23:12

Evgenii


1 Answers

Yes, so long as you declare them @autoclosure(escaping):

Declarations with the autoclosure attribute imply noescape as well, except when passed the optional attribute escaping.

So this should do it:

func myFunc(@autoclosure(escaping) condition: () -> Bool) {
    dispatch_async(dispatch_get_main_queue()) {
        if condition() {
            println("Condition is true")
        }
    }
}
like image 145
Airspeed Velocity Avatar answered Dec 29 '22 10:12

Airspeed Velocity