SwiftData crash when enabling CloudKit for existing users (Free to Pro upgrade)

Hi,

I am implementing a premium feature in my app where CloudKit syncing is available only for "Pro" users.

The Workflow:

  1. Free Users: I initialize the ModelContainer with cloudKitDatabase: .none so their data stays local.
  2. Pro Upgrade: When a user purchases a subscription, I restart the container with cloudKitDatabase: .automatic to enable syncing.

The Problem: If a user starts as "Free" (creates local data) and later upgrades to "Pro", the app crashes immediately upon launch with the following error:

Fatal error: Failed to create ModelContainer: SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer, _explanation: nil)

It seems that SwiftData fails to load the existing data once the configuration changes to expect a CloudKit-backed store.

My Question: Is there a supported way to "toggle" CloudKit on for an existing local dataset without causing this crash? I want the user's existing local data to start syncing once they pay, but currently, it just crashes.

My code:

import Foundation
import SwiftData

public enum DataModelEnum: String {
    case task, calendar
    
    public static let container: ModelContainer = {
        let isSyncEnabled = UserDefaults.isProUser
        let config = ModelConfiguration(
            groupContainer: .identifier("group.com.yourcompany.myApp"),
            cloudKitDatabase: isSyncEnabled ? .automatic : .none
        )
        
        do {
            return try ModelContainer(for: TaskModel.self, CalendarModel.self, configurations: config)
        } catch {
            fatalError("Failed to create ModelContainer: \(error)")
        }
    }()
}
Answered by MichaelBolt in 867986022

Hi everyone,

I wanted to update that I found the issue and it was a mistake on my end, not a SwiftData bug.

The crash loadIssueModelContainer was caused because I had a relationship in one of my models (CalendarModel) that wasn't marked as optional.

Hi everyone,

I wanted to update that I found the issue and it was a mistake on my end, not a SwiftData bug.

The crash loadIssueModelContainer was caused because I had a relationship in one of my models (CalendarModel) that wasn't marked as optional.

SwiftData crash when enabling CloudKit for existing users (Free to Pro upgrade)
 
 
Q