How to run asynchronous code in Swift Playground correctly?

March 17, 20241 min read#swift, #playground

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.

swift_playground

To solve this problem we can import PlaygroundSupport library to gain access to 2 useful APIs of PlaygroundPage object:

solution

Now, when we run the playground again, the programm will be terminated correctly when all async code finishes.

Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2024