🔍 Rules for Adapting Data Models to CloudKit

Get weekly handpicked updates on Swift and SwiftUI!

TL;DR: When using CloudKit with Core Data or SwiftData, avoid unique constraints, undefined types, and non-optional attributes without defaults. Relationships must be optional and have inverse settings. Use lightweight migrations for adjustments, adhering to “add-only” changes.

Background

When using Core Data or SwiftData for cloud synchronization, failing to consider CloudKit’s limitations during the modeling phase can lead to complex issues later. Below are the essential rules and considerations to ensure smooth integration with CloudKit.

Mandatory Rules for Data Models

1. Unique Constraints

Prohibited:

  • Core Data: Unique constraints
  • SwiftData: @Attribute(.unique)

2. Attribute Requirements

  • Attributes must not be non-optional without default values.
  • Allowed configurations:
    • Optional
    • With a default value
    • Optional + Default value

3. Type Restrictions

  • The Core Data Undefined type must not be used.

4. Relationship Requirements

  • All relationships must be optional.
  • All relationships must include inverse relationships.
  • Prohibited configurations:
    • Deny deletion rule
    • Ordered relationships (Ordered)

Key Considerations

Once cloud synchronization is enabled, model changes are limited to lightweight migrations. Developers should plan their data model carefully during the design phase to minimize future modifications.

Model Adjustment Principles

  • Do not delete existing entities or attributes.
  • Do not rename existing entities or attributes.

Recommendations

Follow the principle of “add only, no deletions or modifications”:

  • Only add new entities, attributes, or relationships.

Further Reading