简体   繁体   中英

How to pass a value from an EnvironmentObject to a class instance in SwiftUI?

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 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

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))
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM