Swift & Concurrency (50 Qs)•Part 1: Core Language, Memory & Value Types (1 - 10)
What is `@MainActor` in Swift?
junior LevelCode ExampleswiftCore Language
In Simple Words: A globally unique actor that always executes code on the Main Thread (UI thread):
- Annotating a class, function, or view model with
@MainActorguarantees that all state mutations and UI updates are executed on the main thread, eliminating the classic crash:UIAccessibilityElement not on main thread.
swift
@MainActor
class FeedViewModel: ObservableObject {
@Published var posts: [Post] = []
func loadPosts() async {
let fetched = try? await NetworkService.fetchPosts()
// Automatically runs on Main Thread!
self.posts = fetched ?? []
}
}