Search code examples
swiftswiftuiobservableobjectobservedobject

One ObservedObject needs to take in another ObservedObject as an argument; how do you do this?


struct ContentView {
    @ObservedObject var annotationsVM = AnnotationsVM()
    //I'd like to pass in the ViewModel() declared below into annotationsVM like AnnotationsVM(VModel: Vmodel)
    @ObservedObjects var VModel = ViewModel()

    var body: some View {
        //All the SwiftUI view setup is in here
    }
}

class AnnotationsVM: ObservableObject {
    @ObservedObject var VModel = ViewModel()
    //I'd like to pass in the VModel in content view like: @ObservedObject var VModel: VModel
}

Obviously, I can't pass in the VModel directly upon ContentView creation like I want to because the VModel object hasn't been created yet so it's inaccessible...

Recap: I want to pass in the VModel instance declared in ContentView into the annotationsVM instance (also declare in ContentView)


Solution

  • You can do it in init like this:

    struct ContentView {
        @ObservedObject var annotationsVM: AnnotationsVM
        @ObservedObject var vModel: ViewModel
    
        init() {
            let vm = ViewModel()
            vModel = vm
            annotationsVM = AnnotationsVM(vModel: vm)
        }
    
        var body: some View {
            //All the SwiftUI view setup is in here
        }
    }
    
    class AnnotationsVM: ObservableObject {
        var vModel: ViewModel
    
        init(vModel: ViewModel) {
            vModel = vModel
        }
    }
    

    And you can use @ObservedObject only in View.

    Note: it may be better to pass ViewModels in init as parameters to follow the Dependency Injection pattern.