how to avoid duplicated data, syncing with icloud kit and swiftdata, ios17+

Asked on 03/09/2025

1 search

To avoid duplicated data when syncing with iCloud using SwiftData in iOS 17 and later, you can utilize the new schema macro features introduced in SwiftData. Specifically, the unique macro allows you to define which combinations of your model's properties must remain unique. This ensures that when two model instances share the same unique values, SwiftData will perform an upsert on collision with an existing model, effectively preventing duplicates.

For example, in a hypothetical Trips app, you can use the unique macro to ensure trips are unique across their name, start date, and end date. This allows the app to have multiple trips with the same name, but only if they have different start or end dates. This approach makes it easy to avoid duplicates in the data, as SwiftData can reason about which models represent duplicates and perform updates to the data instead.

For more details, you can refer to the session What’s new in SwiftData (02:43) where the unique macro is discussed.