10

I'm trying to assign the value from an EnvironmentObject called userSettings to a class instance called categoryData, I get an error when trying to assign the value to the class here ObserverCategory(userID: self.userSettings.id)

Error says: Cannot use instance member 'userSettings' within property initializer; property initializers run before 'self' is available

Here's my code:

This is my class for the environment object:

//user settings
final class UserSettings: ObservableObject {
    @Published var name : String = String()
    @Published var id : String = "12345"
}

And next is the code where I'm trying to assign its values:

//user settings
@EnvironmentObject var userSettings: UserSettings

//instance of observer object
@ObservedObject var categoryData = ObserverCategory(userID: userSettings.id)

class ObserverCategory : ObservableObject {

    let userID : String

    init(userID: String) {

        let db = Firestore.firestore().collection("users/\(userID)/categories") //

        db.addSnapshotListener { (snap, err) in
            if err != nil {
                print((err?.localizedDescription)!)
                return
            }

            for doc in snap!.documentChanges {

                //code 

            }
        }
    }
}

Can somebody guide me to solve this error?

Thanks

1 Answer 1

8

Because the @EnvironmentObject and @ObservedObject are initializing at the same time. So you cant use one of them as an argument for another one.

You can make the ObservedObject more lazy. So you can associate it the EnvironmentObject when it's available. for example:

struct CategoryView: View {

    //instance of observer object
    @ObservedObject var categoryData: ObserverCategory

    var body: some View { ,,, }
}

Then pass it like:

struct ContentView: View {

    //user settings
    @EnvironmentObject var userSettings: UserSettings

    var body: some View {
        CategoryView(categoryData: ObserverCategory(userID: userSettings.id))
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Mojtaba Hosseini, thank you for your answer, it makes total sense and works perfectly. I'm learning and this helped me a lot, appreciate your help!
One caveat here is, that the ObservedObject gets recreated every time body of ContentView will be evaluated. Depending on the given view hierarchy, this may result in some "anomalies" where ObserverCategory value will be unexpectedly reset. I thought about using a @StateObject where ObserverCategory will be hold, but without the "direct property wrapper initialisation hack", I cannot think of a way this can be accomplished.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.