MainActor: Keep Your UI on the Main Thread

MainActor isolates UI-facing state and work on the main actor. Annotating a view model can be appropriate. Keep blocking or CPU-heavy work off it; awaiting asynchronous I/O can suspend without blocking the main thread.
MainActor is a global actor whose executor corresponds to the main thread. Use it to isolate UI-facing state and the code that updates that state. Annotating an entire view model can be a sensible design.
Suspension versus blocking
Awaiting asynchronous I/O can suspend the task and let other main-actor work run. That is different from synchronous decoding, computation or blocking calls occupying the main actor. Declaring a function async does not automatically move its computation elsewhere.
Example
A main-actor view model can await an asynchronous request, then update its UI state after the result arrives. Move expensive processing to appropriately isolated work so it does not stall UI updates.
Watch out for
State may change while a task is suspended. Recheck assumptions after awaiting when later work depends on the earlier state.
Sources: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html and https://developer.apple.com/videos/play/wwdc2021/10133/
Interview question
Which task is the most appropriate candidate for being isolated to the MainActor?
- a.Decoding a large JSON payload received from a network request.
- b.Performing a CPU-intensive image filter operation on a background thread.
- c.Assigning a new value to a @Published property that drives a SwiftUI view's text label.Correct
- d.Executing a database query to retrieve user preferences.
Why? this is the answer
The MainActor is specifically designed for UI updates because UI frameworks are not thread-safe. Assigning to a @Published property that drives a SwiftUI view is a direct UI-related operation that must occur on the main thread. The other options describe long-running, CPU-intensive, or I/O-bound tasks that would block the main thread and should be performed on background threads.
Just read this? Test yourself on what you have been reading.
Read the original → developer.apple.com
- #ios
- #swift
- #concurrency
- #actors
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on ios — each one lists the topics its interview covers.
See open roles