Search code examples
swiftswift2grand-central-dispatchfoundation

Grand Central Dispatch with Swift: Use of unresolved identifier GCD


Recently I picked up the book Swift High Performance and tried one of the examples concerned with Apple's Grand Central Dispatch (GCD). I put the following code in a Playground file:

import Foundation
//import XCPlayground
//XCPSetExecutionShouldContinueIndefinitely()

class SalesData {

    var revenue: [Int]
    var average: Int?

    init (revenue: [Int]) {
        self.revenue = revenue
    }

    func calculateAverage() {

        let queue = GCD.backgroundQueue()
        dispatch_async(queue) {

        var sum = 0
        for index in self.revenue.indices {
            sum += self.revenue[index]
        }

        self.average = sum / self.revenue.count
    }
}

Excerpt From: “Swift High Performance.”

However, as can be seen in the attahced sceenshot , XCode tells me that ther is a Use of unresolved identifier GCD. Any idea what I'm missing here?

Thanks!


Solution

  • In the book, they define a struct called GCD which provides that method. So you have to look in the book to get the rest of the code that you need for the example.

    EDIT:

    This is the GCD struct that the book provides:

    struct GCD {
        static func backgroundQueue() -> dispatch_queue_t {
            return dispatch_get_global_queue (QOS_CLASS_BACKGROUND, 0)
        }
    }
    

    It appears on the same page as the example posted in the question.