Using Closures 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 to 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:


Also published on Medium.

Published by Andrew

Leave a Reply

Your email address will not be published. Required fields are marked *

3 + 6 =