Search code examples
swiftgrand-central-dispatchswift3

Check if on correct dispatch queue in Swift 3


I have a few unit tests in which I'd like to test if a callback is called on the correct dispatch queue.

In Swift 2, I compared the label of the current queue to my test queue. However in Swift 3 the DISPATCH_CURRENT_QUEUE_LABEL constant no longer exists.

I did find the dispatch_assert_queue function. Which seems to be what I need, but I'm not sure how to call it.

My Swift 2 code:

let testQueueLabel = "com.example.my-test-queue"
let testQueue = dispatch_queue_create(testQueueLabel, nil)

let currentQueueLabel = String(UTF8String: dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL))!
XCTAssertEqual(currentQueueLabel, testQueueLabel, "callback should be called on specified queue")

Update:

I got confused by the lack of autocomplete, but it is possible to use __dispatch_assert_queue:

if #available(iOS 10.0, *) {
  __dispatch_assert_queue(test1Queue)
}

While this does work for unit tests, it annoyingly stops the whole process with a EXC_BAD_INSTRUCTION instead of only failing a test.


Solution

  • Answering my own question:

    Based on KFDoom's comments, I'm now using setSpecific and getSpecific.

    This creates a key, sets it on the test queue, and later on, gets it again:

    let testQueueLabel = "com.example.my-test-queue"
    let testQueue = DispatchQueue(label: testQueueLabel, attributes: [])
    let testQueueKey = DispatchSpecificKey<Void>()
    
    testQueue.setSpecific(key: testQueueKey, value: ())
    
    // ... later on, to test:
    
    XCTAssertNotNil(DispatchQueue.getSpecific(key: testQueueKey), "callback should be called on specified queue")
    

    Note that there's no value associated with the key (its type is Void), I'm only interested in the existence of the specific, not in it's value.

    Important!
    Make sure to keep a reference to the key, or cleanup after you're done using it. Otherwise a newly created key could use the same memory address, leading to weird behaviour. See: http://tom.lokhorst.eu/2018/02/leaky-abstractions-in-swift-with-dispatchqueue