Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current queue name in swift 3

Tags:

We have function like this in swift 2.2 for printing a log message with the current running thread:

func MyLog(_ message: String) {     if Thread.isMainThread {         print("[MyLog]", message)     } else {         let queuename = String(UTF8String: dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL))! // Error: Cannot convert value of type '()' to expected argument type 'DispatchQueue?'         print("[MyLog] [\(queuename)]", message)     } } 

These code no longer compile in swift 3.0. How do we obtain the queue name now?

like image 450
Yuchen Avatar asked Sep 18 '16 01:09

Yuchen


People also ask

How do I find my current Dispatchqueue?

To get the dispatch queue object you can use [NSOperationQueue currentQueue]. underlyingQueue , which returns your currrent queue as a dispatch_queue_t . - works for main queue!

What is Dispatchqueue in Swift?

Dispatch queues are FIFO queues to which your application can submit tasks in the form of block objects. Dispatch queues execute tasks either serially or concurrently. Work submitted to dispatch queues executes on a pool of threads managed by the system.

What is global queues in Swift?

Global queues: concurrent queues that are shared by the whole system. There are four such queues with different priorities : high, default, low, and background. The background priority queue has the lowest priority and is throttled in any I/O activity to minimize negative system impact.


2 Answers

As Brent Royal-Gordon mentioned in his message on lists.swift.org it's a hole in the current design, but you can use this horrible workaround.

func currentQueueName() -> String? {     let name = __dispatch_queue_get_label(nil)     return String(cString: name, encoding: .utf8) } 
like image 154
Huralnyk Avatar answered Sep 20 '22 06:09

Huralnyk


If you don't like unsafe pointers and c-strings, there is another, safe solution:

if let currentQueueLabel = OperationQueue.current?.underlyingQueue?.label {     print(currentQueueLabel)     // Do something... } 

I don't know any cases when the currentQueueLabel will be nil.

like image 32
kelin Avatar answered Sep 24 '22 06:09

kelin