I’m having trouble solving the following problem. I want to create a workout app where the user can see their workout history and exercise progress. To achieve this, I’m using SwiftData to model the relationship between workouts and exercises in such a way that:
- Exercises are not dependent on workouts.
- Workouts are not dependent on exercises.
Here’s what I have in mind:
import SwiftUI
import SwiftData
@Model
class Workout: Identifiable {
var name: String
var id: UUID
@Relationship(deleteRule: .cascade) var relations: [WorkoutExericise]?
init(name: String = "", id: UUID = UUID()) {
self.name = name
self.id = id
}
}
@Model
class WorkoutExericise: Identifiable {
@Relationship(deleteRule: .cascade, inverse: Workout.relations) var workout: Workout
@Relationship(deleteRule: .cascade, inverse: Exercise.relations) var exercise: Exercise
var sets: [ExerciseSet]
var id: UUID
init(workout: Workout, exercise: Exercise, sets: [ExerciseSet] = [], id: UUID = UUID()) {
self.workout = workout
self.exercise = exercise
self.sets = sets
self.id = id
}
}
@Model
class Exercise: Identifiable {
var name: String
var id: UUID
@Relationship(deleteRule: .cascade) var relations: [WorkoutExericise]?
init(name: String = "", id: UUID = UUID()) {
self.name = name
self.id = id
}
}
struct ExerciseSet: Codable {
var reps: Int
var weight: Float
}
The problem is that this example doesn’t work when deleting a Workout or Exercise that has a relation. Am I overcomplicating things? Or am I just making a mistake? This is my first project with SwiftData.