I have a workout model:
@Model
class Workout {
var id: UUID
var name: String?
@Relationship(deleteRule: .cascade) //when deleting a workout you delete all exericses that happened during that workout
var exercises: [Exercise]?
var startTime: Date?
var endTime: Date?
init(id: UUID) {
self.id = id
}
}
which contains an array of Exercises:
@Model
class Exercise: Identifiable {
var id: UUID
var exerciseName: ExerciseName
@Relationship(deleteRule: .cascade)
var sets: [Set]? //When an Exercise gets Deleted all Sets associated need to get deleted
var date: Date
var workout: Workout? //it can belong to a work but it doesnt have to
init(id: UUID, exerciseName: ExerciseName, date: Date) {
self.id = id
self.exerciseName = exerciseName
self.date = date
}
}
which itself contains an array of Sets:
@Model
class Set: Identifiable{
var id: UUID
var weight: Int
var reps: Int
var isCompleted: Bool
var exercise: Exercise
init(id: UUID, weight: Int, reps: Int,isCompleted: Bool, exercise: Exercise) {
self.id = id
self.weight = weight
self.reps = reps
self.isCompleted = isCompleted
self.exercise = exercise
}
}
I Iterate through the entire Workout Model in a List and what I want to do is have a duplicate button that will create a new Workout but copy all of the Data of the current Workout that got clicked in the list:
Button {
let newWorkout: Workout = Workout(id: UUID())
newWorkout.name = workout.name
//this is not copying at all
newWorkout.exercises = workout.exercises
newWorkout.startTime = Date.now
newWorkout.endTime = Date.now
modelContext.insert(workout)
showDuplicateButton.toggle()
}
Everything is copying correctly except the exercise array which is completely empty, how would I do a deep copy that will copy all of the exercises and sets too into this new workout?