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?
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!
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.
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.
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) }
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With