0

I'm trying to pass a variable object from a SwiftUI View to an observable Object but I'm running into the error: "Cannot use instance member 'loadedGroup' within property initializer; property initializers run before 'self' is available".

Here is how my SwiftUI View class is currently structured


struct LoadedGroupView: View {
    

    @Binding var loadedGroup: group
    
    @StateObject var userData = UserViewModel()
    @StateObject var postData = PostViewModel(passedLoadedGroup: loadedGroup) //error here
    
   
    var body: some View {
      ...
    }
}

Here is my Observable Object class for PostViewModel()


class PostViewModel: ObservableObject {
   
    var loadedGroup: group

    let ref = Firestore.firestore()
    init(passedLoadedGroup: group) {
        group = passedLoadedGroup
    }
}

How would I go about fixing this error because I really need to get that value passed into this observable object class from the View somehow. Thanks for the help!

krish
  • 37
  • 2
  • 10
  • Check this https://stackoverflow.com/a/68480486/14733292 – Raja Kishan Aug 01 '21 at 05:20
  • I just tried that and I get this error now: Property wrapper cannot be applied to a computed property – krish Aug 01 '21 at 05:31
  • Does this answer your question? [Initialize @StateObject with a parameter in SwiftUI](https://stackoverflow.com/questions/62635914/initialize-stateobject-with-a-parameter-in-swiftui) – Phil Dukhov Aug 01 '21 at 05:32
  • Use second approach with init – Raja Kishan Aug 01 '21 at 05:33
  • Thanks the second approach with init worked! – krish Aug 01 '21 at 05:42
  • You probably won't use this solution, because this is not how you should use SwiftUI's `@StateObject`! But consider, when there is a parameter `loadedGroup` that the parent view seems to know about, the easiest way would be to init the ViewModel by the parent and pass it to your view, and have an ObservedObject instead a StateObject to hold it. – CouchDeveloper Aug 01 '21 at 17:10

0 Answers0