How to reuse SwiftData models in multiple apps via Swift Package Manager while defining app-specific relationships?

2 weeks ago 21
ARTICLE AD BOX

Here’s a practical approach to achieve such goal.

1. Keep shared properties in a base model

Define your base model in the Swift package. Mark it open or public so it can be subclassed outside the package:

import SwiftData @Model open class CoreAddress { public var city: String? public var country: String? public var id: UUID? public var label: String? public var latitude: Double? = 0.0 public var longitude: Double? = 0.0 public var streetName: String? public var streetNumber: String? public var zipCode: String? required public init() { } }

This model contains only shared properties. No app-specific relationships here.

**

2. Extend in the app for app-specific relationships**

In each app, subclass the shared model and add your relationships:

import CoreAddress import SwiftData @Model public class Address: CoreAddress { @Relationship(deleteRule: .cascade, inverse: \Department.address) var department: Department? @Relationship(deleteRule: .nullify, inverse: \Person.address) var person: Person? }

3. Use ModelContainer with both models

In SwiftData, ModelContainer needs to know about all models used in your app, including the shared base model and the subclass:

let container = try ModelContainer( for: [CoreAddress.self, Address.self, Department.self, Person.self] )

Note that SwiftData relies on @Model annotations at compile time. You need to include both the base and app-specific models in the container.

Read Entire Article