Getting the current queue and thread name?

The Xcode console logs an identifier indicating the current thread that's running when a message is print()ed from Swift. Some more complex logging systems (e.g. swift-log and console-kit) don't provide that information, and I'm trying to write a logging back-end for swift-log that will.

Thing is, I don't see any way to get the current queue name in Swift. I tried

dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)

But I get "cannot convert value of type '()' to expected argument type 'DispatchQueue?'". Passing nil instead results in "'dispatch_queue_get_label' has been replaced by property 'DispatchQueue.label'".

This is not an unreasonable thing to want to do, and it poses no safety concerns.

Replies

Try this:

import Dispatch

let queue = DispatchQueue(label: "hello-cruel-world")

func main() {
    queue.async {
        print(String(cString: __dispatch_queue_get_label(nil)))
        exit(0)
    }
    dispatchMain()
}

main()

There’s a lot to unpack here:

  • DISPATCH_CURRENT_QUEUE_LABEL is just a macro that returns NULL and is not imported into Swift. Rather, just call dispatch_queue_get_label with nil.

  • In general, dispatch_queue_get_label has been replaced by the label property on a DispatchQueue object.

  • However, that doesn’t cover the case where you pass in NULL to get the current queue’s label. AFAICT there’s no Swift-friendly way to do that and I encourage you to file an enhancement request for that. For example, it might be nice to have a currentQueueLabel static property on DispatchQueue itself.

    Please post your bug number, just for the record.

  • In the meantime, work around this by calling __dispatch_queue_get_label. When a routine, dispatch_queue_get_label, is marked as being refined in Swift, the unrefined version is available via the __ prefix. This doesn’t show up in code completion, but you can happily use it.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"