Ghostboard pixel

Concurrent Code In Playgrounds

Concurrent Code In Playgrounds

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:

import UIKit

let dispatchQueue = DispatchQueue(label: "testQueue")

dispatchQueue.async {
    var sum = 0
    
    for i in 1...10000 {
        sum += i
    }
    
    print("sum: \(sum)")
    
}

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:

import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let dispatchQueue = DispatchQueue(label: "testQueue")


dispatchQueue.async {
    var sum = 0
    
    for i in 1...10000 {
        sum += i
    }
    
    print("sum: \(sum)")
    
}

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:

func sumOfNumbersUpTo(n:Int) -> Int {
    return n*(n+1)/2
}

print("sum: \(sumOfNumbersUpTo(n:10000))")

Video

References:

Image: @  Erce / shutterstock.com