Enabling undo with multi-model schema

.modelContainer(for: MyMode.self, isUndoEnabled: true)

This may work for single model containers, but I have a number of models. I don't see how to enable undo for multiple model containers.

(Don't post while sleepy)

Right in the docs... .modelContainer(for: [MyModel1.self, MyModel2.self], isUndoEnabled: true)

Trying to figure out if this is possible for a sharedModelContainer. When creating a new empty multiplatform app with SwiftData, this code is automatically generated in the App.swift:

import SwiftUI
import SwiftData

@main
struct SwiftDataTestApp: App {
    var sharedModelContainer: 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)")
        }
    }()

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(sharedModelContainer)
    }
}

Is there a way to set isUndoEnabled in this scenario? Doesn't look like ModelContainer(for: Schema...) supports it?

do { let container = try ModelContainer(for: schema, configurations: [modelConfiguration]) container.mainContext.undoManager = UndoManager() return container
} catch { fatalError("Could not create ModelContainer: (error)") }

do {
 let container = try ModelContainer(for: schema, configurations: [modelConfiguration]) 
 container.mainContext.undoManager = UndoManager() 
 return container
} catch { fatalError("Could not create ModelContainer: (error)") }

when you need to undo

@Environment(\.modelContext) var modelContext

modelContext.undoManager?.undo()

This worked for me, in ContentView, add:

@Environment(\.undoManager) var undoManager

and

.onChange(of: undoManager, initial: true) {
    modelContext.undoManager = undoManager
}
Enabling undo with multi-model schema
 
 
Q