Pick the fix
In a @MainActor view model, Task.detached { self.items = try await api.load() } fails to compile in Swift 6. Best fix?
Hint 1 of 2
What does Task {} inherit from a @MainActor context?
Hint 2 of 2
Does an await on the main actor block the UI?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Task { items = try await api.load() }
Correct. The task inherits the main actor, so items can be set directly while load() suspends without blocking.
Why not the others?
- B
Task.detached(priority: .high) { ... }. Priority doesn't change isolation; it still can't set main-actor state synchronously. - C Mark
itemsasnonisolated. A mutable stored property of a main-actor class can't be nonisolated; it would be a data race. - D Wrap the assignment in
DispatchQueue.main.asyncinside the detached task. This mixes GCD into async code and loses structured error handling. It only hides the real fix.