How can I perform Undo&Redo when the Observable class has a SwiftData Model?


I am writing code to be able to perform Undo&Redo with SwiftUI and SwiftData. Unlike usual, there is a Model of SwiftData in the Observable class,

#Preview {
    ContentView()
        .modelContainer(for: Item.self, inMemory: true, isUndoEnabled: true)
@Environment(\.undoManager) var undoManager

but it doesn't work. How should I describe the isUndoEnabled: true option and the undoManager?

import SwiftData

@Observable class SwiftDataCoordinator {
    
    static let shared = SwiftDataCoordinator()

    var items = [Item]()
    
    let modelContainer: ModelContainer = {
        let schema = Schema([
            Item.self
        ])
        
        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

        do {
            return try ModelContainer(for: schema, configurations: [modelConfiguration])
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()
}

It doesn't seem that your code snippet shows how you use undoManager in any way, like calling undo() or redo(), or setting an action name (setActionName(_:))...

So what doesn't work? If you can elaborate how SwiftData undo behaves differently from your expectation with a step by step guide, maybe folks here can better help?

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

How can I perform Undo&Redo when the Observable class has a SwiftData Model?

 
 
Q