Home > Software engineering >  Error: Cannot infer contextual base in reference to member 'environmentObject'
Error: Cannot infer contextual base in reference to member 'environmentObject'

Time:08-07

After Xcode 14/iOS16 .environtmentObject is showing the error Cannot infer contextual base in reference to member 'environmentObject'

What does this error mean in context to the code below and in plain terms?

@main
struct App: App {
    
    @StateObject var sessionManager = SessionManager.shared
    
    var body: some Scene {
        WindowGroup {
                if sessionManager.isAuthenticated  {
                    MainScreen()
                        .transition(.slide)
                } else {
                    SigninScreen()
                        .transition(.slide)
                }
                .environmentObject(sessionManager)
        }
    }
}

CodePudding user response:

View modifier should be attached to a view, not to a if/else operator

    WindowGroup {
        Group {      // << ... or any view container !!
            if sessionManager.isAuthenticated  {
                MainScreen()
                    .transition(.slide)
            } else {
                SigninScreen()
                    .transition(.slide)
            }
        }
        .environmentObject(sessionManager)  // << here !!
    }
  • Related