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)")
        }
    }()
}
How can I perform Undo&Redo when the Observable class has a SwiftData Model?

 
 
Q