Swift Playground is a great tool for quick experimentation with Swift code. While most of the time, we just need synchronous code for such experimentations. But some time, we also want to write async code, such as fetching data from remote server, in Swift Playground.
Swift Playground by default execute the code synchronously, from top to bottom of our program. When running async code, we will see that the problem could never be terminated and will run forever.
To solve this problem we can import PlaygroundSupport
library to gain access to 2 useful APIs of PlaygroundPage object:
- needsIndefiniteExecution: A Boolean value that indicates whether indefinite execution is enabled.
- finishExecution()
Now, when we run the playground again, the programm will be terminated correctly when all async code finishes.