MainActor

The interviewer asks

“What is MainActor? When do you need it?”

How to answer

@MainActor is the global actor that represents the main thread. Code isolated to it can only run there, and in Swift 6 language mode the compiler enforces that at compile time: calling main-actor code from elsewhere requires await, and touching main-actor state from the wrong context is an error. You need it for anything that drives UI, so UIKit views and controllers and SwiftUI's View are already @MainActor, and UI models should be @MainActor @Observable final class. New app targets (since Xcode 26) use Swift 6.2 default MainActor isolation, so unannotated code is main-actor there, but I still write it explicitly.

Key points

  • Apply @MainActor to a type (all members isolated), a single method or property, or a closure ({ @MainActor in ... })
  • View, UIView, UIViewController are @MainActor; so are body, button actions and .task closures
  • Task { } inherits the current isolation: started from a @MainActor method, its body runs on the main actor, so await MainActor.run there is redundant
  • await inside a main-actor method suspends without blocking; the method resumes on the main actor
  • Isolation makes a class Sendable; @Observable alone does not
  • Swift 6.2: default MainActor isolation per module (new app targets yes, packages no); opt out with nonisolated or @concurrent
  • Isolated conformances (Swift 6.2): extension Model: @MainActor SomeProtocol lets a main-actor type conform to a nonisolated protocol

If they dig deeper

When MainActor.run is still right (non-isolated async code that needs one main-actor hop). MainActor.assumeIsolated for callbacks documented to arrive on main (it traps otherwise). Why async doesn't mean "background": a @MainActor async function runs on main between suspensions, so CPU work belongs in a @concurrent function. isolated deinit (Swift 6.2) to clean up main-actor state. How @preconcurrency delegates and Task { @MainActor in } bridge legacy callbacks.

Common pitfalls

Doing heavy decoding or image work inside a @MainActor method, which blocks the UI even though it's async. Wrapping every UI update in MainActor.run instead of isolating the type. Using Task.detached to "get off main" and then needing to hop back. Calling MainActor.assumeIsolated from a background callback (crash). Relying on GCD habits: the compiler treats a DispatchQueue.main.async { } closure as main-actor, but a closure on any other queue that touches main-actor state is diagnosed, so isolate the code instead of hopping queues by hand.

How to use it

swift
import SwiftUI

@MainActor
@Observable
final class ProfileModel {
    private(set) var name = ""
    private(set) var isLoading = false
    private let api: any ProfileAPI                // Sendable service
    @ObservationIgnored private var refreshTask: Task<Void, Never>?

    init(api: any ProfileAPI) { self.api = api }

    func refresh() {                               // sync entry point (button)
        refreshTask?.cancel()                      // owned: a second tap replaces the first
        refreshTask = Task {                       // inherits @MainActor
            isLoading = true
            defer { isLoading = false }
            name = (try? await api.fetchName()) ?? "Unknown"  // fallback on failure; no MainActor.run
        }
    }
}

struct ProfileView: View {                         // View is @MainActor
    @State private var model = ProfileModel(api: LiveProfileAPI())

    var body: some View {
        Text(model.name)
            .onAppear { model.refresh() }          // sync call, same actor
    }
}

Isolated conformance and a legacy callback boundary (Swift 6.2):

swift
protocol DownloadDelegate: AnyObject {             // nonisolated protocol
    func downloadDidFinish(_ url: URL)
}

extension ProfileModel: @MainActor DownloadDelegate {
    func downloadDidFinish(_ url: URL) { refresh() }   // stays main-actor
}

// A C/ObjC callback on an unknown thread: hop explicitly
nonisolated func onLegacyEvent(model: ProfileModel) {
    Task { @MainActor in model.refresh() }
}

Best practices

  • Isolate UI types and models to @MainActor instead of hopping at each call site
  • Rely on Task inheritance inside main-actor code; reserve await MainActor.run for non-isolated async code
  • Move CPU-heavy work to a @concurrent function; keep main-actor methods short
  • Make services Sendable (value types, actors or Mutex-backed classes) so main-actor code can call them
  • Use isolated conformances rather than nonisolated workarounds when a main-actor type adopts a plain protocol

Related concepts

  • Actors, nonisolated and @concurrent, Sendable, Task inheritance, Observable macro, @preconcurrency