How to use @autoclosure parameter in an asynchronous block in Swift?

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

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

I get the following error.

Using the @noescape close option may allow it to exit.

Is it possible to call the @autoclosure parameter asynchronously?

Tested in Xcode 6.4 (6E23).

+4
source share
1 answer

Yes, if you declare them @autoclosure(escaping):

Declarations with an attribute autoclosureimply noescapeunless an optional attribute is passed escaping.

So this should do it:

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

Source: https://habr.com/ru/post/1589312/


All Articles