How to turn On/Off iCloudKitSync on a SwiftUI application

I'm trying to give the user the ability to decide whether they want to sync to CloudKit or not by turning On or Off a Switch located somewhere in the app settings screen but I'm not sure how to do it in SwiftUI.

The following code successfully stops the sync to CloudKit by setting the cloud kit container options to nil description.cloudKitContainerOptions = nil.

    class CoreDataManager{    
        static let instance = CoreDataManager()

        let container: NSPersistentCloudKitContainer
        let context: NSManagedObjectContext
        
        init(){
            container = NSPersistentCloudKitContainer(name: "CoreDataContainer")
            
            guard let description = container.persistentStoreDescriptions.first else{
                fatalError("###\(#function): Failed to retrieve a persistent store description.")
            }

            description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
            description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)

            description.cloudKitContainerOptions = nil

            container.loadPersistentStores { (description, error) in
                if let error = error{
                    print("Error loading Core Data. \(error)")
                }
            }
            container.viewContext.automaticallyMergesChangesFromParent = true
            context = container.viewContext
        }
        
        func save(){
            do{
                try context.save()
                print("Saved successfully!")
            }catch let error{
                print("Error saving Core Data. \(error.localizedDescription)")
            }
        }
    }

What I ultimately want is to be able to control the syncing process with an @AppStore property or some sort of property, something like this...

class CoreDataManager{
    @AppStorage("iCloudSync") private var iCloudSync = false

    //missing code...
    init(){
        if !iCloudSync{
            description.cloudKitContainerOptions = nil
        }
    }
    //missing code...
}

But I'm facing a couple of issues, one, I'm getting an error when using the iCloudSync wrapper variable and the second one and the most difficult for me to solve is the fact that I need to make the persistent storage reload when the switch changes from On to Off of vise-versa.

Any idea how can I structure my code so I can control the syncing process and be able to reload the persistent storage when the switch changes?

By the way and just for reference, here is how I'm using the CoreDataManager class in my view model.

    class CarViewModel: ObservableObject{
        let manager = CoreDataManager.instance
        @Published var cars: [Car] = []
        
        init(){
            getCars()
        }
        func addCar(){}
        func getCars(){}
        func deleteCar(){}
        func save(){
            self.manager.save()
        }
    }

Replies

How much data are you trying to synchronize when the user has the feature enabled? You could have two containers, one that is local only, and the other that is the cloud container. I'm not sure that simply 'flipping the switch' would propagate / synchronize as fast as the user is expecting.

The difficult part with this approach would be migrating the data from one store to the other as they change the value.

Not really a lot of data, about 10-50 objects with 10 properties each. So you think the most appropriate thing to do is use the local container if sync is off and switch to cloudKit container if it's on? My main struggle is not knowing how to structure my code in a way that I can turn On/Off sync on runtime from other views to test it and see if it will work.