2

I'm using a DataStore environmentObject to pass data around my app, however I'm at a point where I needed to create a specific View Model class for a view, but I need to be able to pass the instance of my dataStore to my WorkoutDetailViewModel but can't figure out a way to do it. I tried passing it in as a parameter to WorkoutDetailViewModel, but the compiler complains Cannot use instance member 'dataStore' within property initializer; property initializers run before 'self' is available. How else can I do this?

struct NewWorkoutDetailView: View {
    
   @EnvironmentObject var dataStore: DataStore
   
    
   @StateObject var workoutDetailViewModel = WorkoutDetailViewModel(dataStore: dataStore)
    
    
    var body: some View {

    }

 }


final class WorkoutDetailViewModel: ObservableObject {

    var dataStore: DataStore
    
    @Published var fullyLoadedWorkout: TrackerWorkout?
    @Published var notes: String = ""
    @Published var workoutImage = UIImage()
    @Published var workoutLocation: String = ""
    
    
    public func editWorkout() {
       dataStore.loadWorkouts() 
    }

 }
GarySabo
  • 5,806
  • 5
  • 49
  • 124
  • hi interesting, not sure if this could be of use https://stackoverflow.com/questions/59491675/swiftui-how-to-pass-environmentobject-into-view-model – jspcal Jul 23 '21 at 20:04
  • @jspcal thanks yes one of the answer's worked perfectly. – GarySabo Jul 23 '21 at 21:23
  • 1
    I have to say that the answer you referenced is pretty awful. The correct solution is that you should pass the view model in from the superview via the initialiser; don't have the view instantiate it's own view model instance. – Paulw11 Jul 23 '21 at 21:53

0 Answers0