Why SwiftUI Table doesn‘t track changes in @Observable object? Is there are bug in SwiftUI?

Hello!
I try to build Table with Observation framework but Table doesn't track changes in data. However, the List keeps track.

@Observable
final class Item: Identifiable {
    var id: UUID
    var value: Int
    
    init(value: Int) {
        self.id = UUID()
        self.value = value
    }
}

@Observable
final class AppModel {
    
    var items: [Item]
    
    init() {
        var items: [Item] = []
        for i in 0...10 {
            items.append(Item(value: i))
        }
        self.items = items
    }
    
    func updateValue() {
        let index = Int.random(in: 0..<items.count)
        items[index].value = Int.random(in: 200...300)
    }
    
    func startTimer() {
        let _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
            self.updateValue()
        }
    }
}

@main
struct TestApp: App {
    
    @State private var appModel = AppModel()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(appModel)
        }
    }
}  

  struct ContentView: View {
    
    @Environment(AppModel.self) private var appModel
    
    var body: some View {
        VStack {
            Table(appModel.items) {
                TableColumn("Value") {
                    Text("\($0.value)")
                }
            }
            List(appModel.items) {
                Text("\($0.value)")
            }
        }
        .padding()
        .frame(minHeight: 640)
        .onAppear {
            appModel.startTimer()
        }
    }
}

What am I missing? Thank you.
On stackoverflow somebody says that it’s a bug.

Test app on Google drive.

As noted below this code works on iOS but not works on macOS.

I tried your code and it works, both the Table and List are updating. I used iPad Playgrounds, not sure why it isn’t working for you.

Very interesting! This code works on iOS but doesn't work on macOS.

That seems like a bug to me; if you wouldn't mind - please file a feedback via feedbackassistant.apple.com since that is likely more-todo-with-swiftui than per se Observation itself.

1 Like

Feedback FB13673492

2 Likes

I ran into this problem on macOS too. I got it to work by changing the data the Table uses from "@Observable class..." to "struct".

In your case, change:

"@Observable final class Item: Identifiable {"

to:

"struct Item: Identifiable {"

I verified that this change to your example works on my mac running 14.5 with Xcode 15.4.

Issues was solved in macOS 15. But in macOS 14.7, this bug still persists.

There is another issue in SwiftUI Table in macOS 15 and 14.7. SwiftUI Table unexpectedly deselects selected rows when updating data. It doesn't matter what we use as a table model: struct or observable. SwiftUI List works perfectly!