Daily iOS
SwiftUI

SwiftUI async MainActor state

A SwiftUI order list ViewModel calls an async API and then changes the screen state with the result. Under Swift 6 strict concurrency, which part of this ViewModel would you isolate with @MainActor?

How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

Put @MainActor on the whole ViewModel class (the @Observable type) rather than picking a few properties. The screen state properties and the methods that change them then all run on the main actor only; the network call hands off to another executor with await and resumes on main when the response arrives, so changing state after that is safe.

Share a question