I have a subview that needs a model object to work with, this view can be navigated to from a list of existing workouts or without a workout. The functionality I want is to use the passed workout if it exists or if it doesn’t to immidielty Create a workout and insert it into modelContext so I can take advantage or my SwiftData relationships.
so far I have tried to use init for this:
var workout : Workout
var passedWorkout : Workout?
//If a workout was passed we assign it and if it was not we create a new one
init() {
if let unwrappedWorkout = passedWorkout {
workout = unwrappedWorkout
}
else {
workout = Workout(id: UUID())
print("inserting (workout.id)")
modelContext.insert(workout)
}
}
but then it expects the workout to be passed so I tried changing workout to be a @State and it still says it expects it to be passed in, I also tried moving this code from init to onAppear and it produces the same error. How do I pass an optional value to a subview and then unwrap it to insert into modelContext as soon as the view is created.