Spot the bug
This compiles, but the feed sometimes shows glitches and Thread Sanitizer reports a data race. Tap the line where UI state is changed off the main actor.
@Observablefinal class FeedModel {var posts: [Post] = []func refresh() {Task.detached {let new = try await API.posts()self.posts = new}}}
Hint 1 of 2
Which line changes state the UI observes?
Hint 2 of 2
Where does a detached task run?
Choose an answer, then open Show answer below to check it.
Show answer
- Answer: line 7
self.posts = new
Line 7 sets observed UI state from a detached task on the concurrent pool while SwiftUI reads it on the main thread. Mark the class @MainActor and use Task {} so the assignment happens on the main actor; then the compiler checks every access.