Check if on correct dispatch queue in Swift 3

Tests based on KFDoom's answer:

import XCTest
import Dispatch

class TestQueue: XCTestCase {

    func testWithSpecificKey() {
        let queue = DispatchQueue(label: "label")

        let key = DispatchSpecificKey<Void>()
        queue.setSpecific(key:key, value:())

        let expectation1 = expectation(withDescription: "main")
        let expectation2 = expectation(withDescription: "queue")

        DispatchQueue.main.async {
            if (DispatchQueue.getSpecific(key: key) == nil) {
                expectation1.fulfill()
            }
        }

        queue.async {
            if (DispatchQueue.getSpecific(key: key) != nil) {
                expectation2.fulfill()
            }
        }

        waitForExpectations(withTimeout: 1, handler: nil)
    }

    func testWithPrecondition() {
        let queue = DispatchQueue(label: "label")

        let expectation1 = expectation(withDescription: "main")
        let expectation2 = expectation(withDescription: "queue")

        DispatchQueue.main.async {
            dispatchPrecondition(condition: .notOnQueue(queue))
            expectation1.fulfill()
        }

        queue.async {
            dispatchPrecondition(condition: .onQueue(queue))
            expectation2.fulfill()
        }

        waitForExpectations(withTimeout: 1, handler: nil)
    }

}

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


Use dispatchPrecondition(.onQueue(expectedQueue)), the Swift 3 API replacement for the dispatch_assert_queue() C API.

This was covered in the WWDC 2016 GCD session (21:00, Slide 128): https://developer.apple.com/videos/play/wwdc2016/720/