Best way to run an anonymous function on the main actor

Now that we have the new concurrency features in Swift 5.5, I'm wondering what the best way is to perform a small bit of work on the main actor from an asynchronous function. I know I can create a dedicated function and decorate it with @MainActor, but sometimes the work is too trivial to get a named function.

In the past, I would do this with GCD, e.g.

DispatchQueue.main.async { print("Okay, we're done")

Is that still the recommended way to run small, anonymous functions on the main actor? Or is there a newer way, less tied to GCD?

From the Closures section in SE-0316, I guess you can do

await { @MainActor in print("Okay, we're done") }()


Task { @MainActor in print("Okay, we're done") }
Task.detached { @MainActor in print("Okay, we're done") }

You can call directly:

await {
  print("Okay, we're done")

That’ll suspend the calling function and resume it once the main actor is done which mightn’t be necessary/possibly wasteful. What if you just simply want to “fire and forget” some work off to the Main actor?

The only way to “fire and forget” are unstructured tasks. This is on purpose, we try to dissuade from using fire and forget most of the time.

Having that said, it is:

Task { @MainActor in hello() }
// or better 
@MainActor func someFunctionOnMainActor() {}
Task { await someFunctionOnMainActor() }
1 Like
Terms of Service

Privacy Policy

Cookie Policy