Migrating a swiftData project to CloudKit to implement iCloudSync.

My project is using swiftData and I want to implement iCloud sync in it. Now, my data base doesnt have any optional attributes or relationships and CloudKit wants them to be optional.

So, rather than editing all code with unwrapping code for the optionals, how can I provide a bridge that does so in the last stage of actually saving to the store? Sort of, capture it in a proxy object before writing and after reading from the store.

Is there a neat way that can save a lot of debugging? I have code snippets from chat gpt and they are hard to debug. This is my first project in swiftUI.

Thanks. Neerav

Answered by joadan in 840531022

You could make the model properties private and rename them and then add computed properties with the old name that you can access from outside the class.

var someString: String

could be replaced with

private var someStringStored: String?

var someString: String {
    get { someStringStored ?? "" }
    set { someStringStored = newValue }
}


Accepted Answer

You could make the model properties private and rename them and then add computed properties with the old name that you can access from outside the class.

var someString: String

could be replaced with

private var someStringStored: String?

var someString: String {
    get { someStringStored ?? "" }
    set { someStringStored = newValue }
}


What do I do with relationships?

class Category {
var expenses: [Expense] = []
}

The same. Just make sure you always initialize the to-many properties to an empty array as you have done in your example

Migrating a swiftData project to CloudKit to implement iCloudSync.
 
 
Q