Using Completion Handlers in Xcode Playgrounds

When starting to learn Swift, you will eventually want to explore creating Swift closures as asynchronous completion handlers. Naturally, you’ll try and fire up a Playground and wire up a function that takes another function as an argument. But when you want to test your completion execution, you might have noticed that the debug console printed a mysterious () type instead of what you expected. What Xcode Playground is doing is saying that there was a function that executed, but the current page has completed its execution.

If you would like to tell the Xcode Playground to continue executing your code (including the code in the completion handler) you need t0 access the currentPage of the XCPlayground.XCPlaygroundPage and tell it to do so. This is done by executing XCPlayground.XCPlaygroundPage.currentPage.finishExecution() after importing XCPlayground at the top of your Xcode Playground code. I wrote up this Gist as an example:

Originally published at Haiku Robot.

Like what you read? Give Andrew Sowers a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.