i presume that for this question … the answer is "no"?
That’s not correct. The trick here is the @MainActor
attribute, as discussed here. Consider this snippet:
@IBAction
private func testAction(_ sender: Any) {
NSLog("testAction(_:)")
async { @MainActor in
NSLog("closure")
await self.delay()
}
}
private func delay() async {
NSLog("delay()")
await Task.sleep(1 * 1000 * 1000 * 1000)
}
This prints:
2021-06-30 09:50:38.913443+0100 xxsi13[54758:3760684] testAction(_:)
2021-06-30 09:50:38.914759+0100 xxsi13[54758:3760684] closure
2021-06-30 09:50:38.914915+0100 xxsi13[54758:3760684] delay()
Note how the thread ID (3760684) is the same in all cases.
IMPORTANT I tested this in Xcode 13.0b2 targeting the iOS 15.0 simulator. To get it to work I had to set the SWIFT_DEBUG_CONCURRENCY_ENABLE_COOPERATIVE_QUEUES
environment variable, but I believe that’s because of an implementation bug rather than anything fundamentally wrong with my code.
Having said that, this stuff is moving very fast so I could be wrong (-:
Oh, one last thing: The Swift concurrency design has an affordance for something called a custom executor, which will give you more control over how actors integrate with queues (or threads). However, this isn’t yet designed, let alone implemented. If you’re curious, see Support custom executors in Swift concurrency.
Share and Enjoy
Quinn “The Eskimo!” @ DTS @ Apple