My model class includes an array of objects that have some properties in common and some specific to only a subset. That sounds like a use case for a protocol
and inheritance. However, I can't get SwiftData to compile this.
Minimal example:
import Foundation
import SwiftData
@Model
class Workout {
var startTime: Date
var endTime: Date?
var activities: [Activity]
init(startTime: Date, endTime: Date? = nil, activities: [Activity]) {
self.startTime = startTime
self.endTime = endTime
self.activities = activities
}
}
protocol Activity {
var calories: Int {get}
}
@Model
class Run: Activity {
var calories: Int
var steps: Int
init(calories: Int, steps: Int) {
self.calories = calories
self.steps = steps
}
}
@Model
class Swim: Activity {
var calories: Int
var lanes: Int
init(calories: Int, lanes: Int) {
self.calories = calories
self.lanes = lanes
}
}
The error Type 'any Activity' cannot conform to 'PersistentModel'
occurs in the generated code for the array:
I watched the WWDC videos, read through the docs and looked at all example projects I could find — nowhere is this problem tackled.
Does anyone have an idea either how to make SwiftData to support this or how to model the data in a compatible way?
This might help you.