1

I'm trying to understand concurrency and can't figure out why this is the escaping closure is not being called.

var closure: (() -> ()) = {
    defer { print("inner") }
}

func outer(asyncClosure: @escaping (() -> ())) {
    defer { print("outer") }

    DispatchQueue.main.async { asyncClosure() }
}

outer(asyncClosure: closure)

// output is "outer" only

Why is my escaping closure not being called? It's an async function on the main queue and is not blocking anything.

meowmeowmeow
  • 623
  • 4
  • 16
  • There's probably something wrong with your XCode or you're testing this code in `XCUnitTest`. This code works just fine (just tested!). In `XCUnitTest`s for `@escaping` closures you have to tell the test class to wait for sometime. (search for `expectations` in Unit Tests) – farzadshbfn Oct 08 '17 at 13:51

1 Answers1

2

I'm guessing you are running this in the Playground? The playground may "finished" running at the closing brace of outer() and the async block that comes after is not run.

Try:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true