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() } } 
3
  • hi interesting, not sure if this could be of use stackoverflow.com/questions/59491675/… Commented Jul 23, 2021 at 20:04
  • @jspcal thanks yes one of the answer's worked perfectly. 👍 Commented Jul 23, 2021 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. Commented Jul 23, 2021 at 21:53

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.