user11371080
user11371080

Reputation:

SwiftUI - Pass environment object to a View

My goal is to pass a "Session" object to a View so I can access its contents. Currently I am passing the session instance as an environmentObject to a TabView so that all tabs have access to this session.

Here is my session class:

class Session: ObservableObject {
    let auth = Auth.auth()

    @Published var signedIn = false
    
    var isSignedIn: Bool {
        return auth.currentUser != nil
    }
}

In my app struct I have the TabView and put the session in the environmentObject modifier:

struct app: App {

    @StateObject var session = Session()

    TabView {
        // Tabs redacted for easy viewing
    }
    .environmentObject(session)
}

And finally a View I am hoping to use this session environment object in:

struct NewListView: View {
    @EnvironmentObject var session: Session

    var body: some View {
        HStack {
            Text(session.$signedIn)
        }
    }
}

I was expecting this to work. Instead I am getting this error:

Initializer 'init(_:)' requires that 'Published.Publisher' conform to 'StringProtocol'

Am I understanding environment variables incorrectly here?

Upvotes: 1

Views: 1441

Answers (1)

keyvan yaghoubian
keyvan yaghoubian

Reputation: 322

Remove $

struct NewListView: View {
    @EnvironmentObject var session: Session

    var body: some View {
        HStack {
            Text("\(session.signedIn)")
        }
    }
}

Upvotes: 0

Related Questions