1

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.

3
  • 3
    Item is supposed to be a struct, just struct Item: Identifiable { let id = UUID() var value: Int } Commented Feb 10, 2024 at 5:55
  • @vadian, thank you! This works. Can you write this comment in answer and explain why Item must be the struct? Commented Feb 10, 2024 at 7:34
  • I think Apple just forgot to implement this for Table. Commented Feb 10, 2024 at 8:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.