Which Thread Are You Using in Swift?

You surely should know!

Steven Curtis
2 min readJan 15, 2023
Photo by Bozhin Karaivanov on Unsplash

Yeah, after writing about that threads should be handled by the view model in MVVM and writing about GDC in Swift I’ve still got one question.

**How do you know which thread you’re using in your Swift code.*

There’s a simple extension for that. I’ve written such a thing.

The extension

For once I don’t think that it is necessary to provide you with the code for this (although it is right in the repo).

Effectively we can return the OperationQueue, DispatchQueue or current thread.

I’m returning the result to the console, of course you could do anything you wanted with the resultant String

extension Thread {
var threadName: String {
if let currentOperationQueue = OperationQueue.current?.name {
return "OperationQueue: \(currentOperationQueue)"
} else if let underlyingDispatchQueue = OperationQueue.current?.underlyingQueue?.label {
return "DispatchQueue: \(underlyingDispatchQueue)"
} else {
let name = __dispatch_queue_get_label(nil)
return String(cString: name, encoding: .utf8) ?? Thread.current.description
}
}
}

--

--

No responses yet