Daniel Tull: Today I Learned

Annotating a closure with @MainActor

Wednesday, 16 February 2022

With the new Swift concurrency features, you can annotate types and functions to run on the MainActor. Today I learned that you can also annotate closures as well:

Task { @MainActor in
    let value = await someAsyncFunction()
    displayValue(value) // runs on the main actor
}

This ensures the closure continues on the main actor after awaiting asynchronous function.

Thanks to Davide De Franceschi for pointing this out!