setting a variable on main thread

Hi,

when working with SwiftUI @Published variables need to be set from the main thread, but at the same time, cannot be defined as @MainActor.

The easy solution is a simple forced sync or async execution on the main thread, but it seems like this does not exist in the world of async/await and Tasks - at least I did not find it. Instead I found that all demo's from Apple is a quite sad solution. The full method is marked as @MainActor even though this is often only relevant for the last line. The question is either that I can execute a setter on main only OR that I can mark my SwiftUI code as being on main and thus being able to accept @MainActor @Published

Is there really no solution? If so where do I have to propose/request a solution for this.

I feel like every developer had written his own version of Thread.performOnMain, but here I want something using Task and that the compiler can verify.

All the best Christoph

Answered by ChristophV in 705647022

Ups looks like exactly this exists as MainActor.run :)

Accepted Answer

Ups looks like exactly this exists as MainActor.run :)

setting a variable on main thread
 
 
Q