Concurrent Code In Playgrounds

concurrent code

Playgrounds are a very powerful tool, but it hasn’t been possible to execute concurrent code yet. But since Xcode 8, you can do so.

Hint: This post is using Swift 3 and Xcode 8

Let’s start by looking at a simple playground example:

We wan’t to calculate the sum of the numbers 1 to 10000 concurrently. For that we are using the new Grand Central Dispatch syntax of Swift 3. But when we run the playground, the loop will be executed just a few times and no result will ever be displayed.

This happens due to the nature of Playgrounds: They are like scripts, and when the last operation has been executed, the whole process will be terminated and tasks in the background cannot be continued.

In Xcode 8 there’s a new helper class called  PlaygroundPage that has a function which allows a Playground to live indefinitely. In order to use this class, you have to import PlaygroundSupport. Let’s make some code adjustments:

Now the dispatch queue can execute until the work is finished. This is particularly helpful for network calls.

By the way: There’s a much easier and quicker way to calculate the sum of the first n numbers:



Image: @  Erce /