What is @MainActor and why does it matter?
thread safety for UI updates.
@MainActor is a global actor guaranteeing code runs on the main thread; annotate UI-updating types or methods so post-network state changes are main-thread safe.
WHAT THIS TESTS This confirms you understand that all UIKit and SwiftUI UI work must happen on the main thread, and that @MainActor is the modern, compiler-enforced way to guarantee that within structured concurrency.
A GOOD ANSWER COVERS UIKit and SwiftUI are not thread-safe and require UI updates on the main thread; doing otherwise causes crashes, visual glitches, or undefined behavior. @MainActor is a global actor whose executor is the main thread, so any function, property, or type annotated with it is guaranteed to run there, and the compiler diagnoses violations. You typically annotate a view model class with @MainActor so all its published state mutations are main-thread safe, or mark a specific method. This matters most after a network call: when you await URLSession, the continuation may resume on a background thread, so assigning the result to a @Published property or a UILabel from there is unsafe. If the surrounding type is @MainActor, the resumption hops back to the main actor automatically. The old equivalent was DispatchQueue.main.async, but @MainActor makes the requirement explicit and statically checked.
COMMON WRONG ANSWERS Thinking await guarantees you return to the main thread by itself. Updating UI directly in a Task without main-actor isolation. Believing @MainActor is just a runtime assertion rather than a compile-time guarantee.
LIKELY FOLLOW-UPS Where does an awaited call resume by default? How does @MainActor differ from DispatchQueue.main.async? Can you mark just one method? How does it interact with nonisolated members?
ONE CONCRETE EXAMPLE @MainActor final class UsersViewModel: ObservableObject has @Published var users: [User] and func load() async { users = try await api.fetchUsers() }. Because the class is main-actor isolated, even though fetchUsers suspends and resumes on a background executor, the assignment to users runs on the main thread, so the SwiftUI view updates safely. Removing the annotation could assign from a background thread and crash or corrupt the UI.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.