Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 581
Tom Lokhorst Avatar asked Jun 21 '16 18:06

Tom Lokhorst


People also ask

How do I find the current queue in Swift?

NSOperationQueue has the class function [NSOperationQueue currentQueue] , which returns the current queue as a NSOperationQueue object. To get the dispatch queue object you can use [NSOperationQueue currentQueue].

Is DispatchQueue global serial or concurrent?

The main dispatch queue is a globally available serial queue executing tasks on the application's main thread.

What is the use of DispatchQueue in Swift?

A dispatch queue that is bound to the app's main thread and executes tasks serially on that thread. A dispatch queue that executes tasks concurrently using threads from the global thread pool. A dispatch queue that executes tasks serially in first-in, first-out (FIFO) order.

How many types of dispatch queues are there?

There are two types of dispatch queues, serial dispatch queues and concurrent dispatch queues.


1 Answers

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/

like image 104
das Avatar answered Oct 10 '22 00:10

das