Running with CloudKit and Swift 6

Hello, everyone,

I've started a thread and got a recommendation from DTS Engineer to move the conversation here.

The sample code for https://developer.apple.com/documentation/coredata/sharing-core-data-objects-between-icloud-users is with Swift 5. I have a Swift 6 project and I'm running into issue porting the sample code.

I've found that NSManagedObjectContext is sendable (https://fatbobman.com/en/posts/sendable-nsmanagedobjectcontext/). From it I can get the persistence controller, and from it I get the stores and this solves the Swift 6 migration path and looks good. i.e. not rely on the private and shared references to the persistence stores, I'll be getting them from the context.

I've also notices that once I start to change the PersistenceController from lazy vars for lazy var previewContainer: NSPersistentCloudKitContainer and lazy var persistentContainer: NSPersistentCloudKitContainer to

struct PersistenceController {
    static let shared = PersistenceController()

    @MainActor
    static let preview: PersistenceController = {
        let result = PersistenceController(inMemory: true)

which is the default pattern for new CoreData applications (Xcode 26 / Xcode 27) I start getting preview crashes similar to https://developer.apple.com/forums/thread/654126.

It turns out this is because of let persistenceController = PersistenceController.shared in the App. Quite unexpected.

The persistence controller looks more suitable for actor based on the CloudKit sharing requirements. I saw such question on WWDC 26, however there was not enough time for an answer - is a good pattern to have the PersistenceController as an actor or in another way. Which is that most swiftly way for Swift 6?

Running with CloudKit and Swift 6
 
 
Q