How to get the current queue name in swift 3

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.


Now DispatchQueue has label property.

The label you assigned to the dispatch queue at creation time.

var label: String { get } 

It seems been existed from first, maybe not been exposed via public API.

macOS 10.10+

And please use this only to obtain human-readable labels. Not to identify each GCDQ.

If you want to check whether your code is running on certain GCDQ, you can use dispatchPrecondition(...) function.


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)
}

Tags:

Swift

Swift3