SwiftUI @Binding Initialize

CRE8IT picture CRE8IT · Jun 20, 2019 · Viewed 21.4k times · Source

Been playing around with SwiftUI and understood the concept of BindableObjects etc so far (at least I hope I do).

I bumped into a stupid problem I can't seem to find an answer for: How do you initialize a @Binding variable?

I have the following code:

struct LoggedInView : View {

    @Binding var dismissView: Bool

    var body: some View {
        VStack {
            Text("Hello World")
        }
    }
}

In my preview code, I want to pass that parameter of type Binding<Bool>:

#if DEBUG
struct LoggedInView_Previews : PreviewProvider {
    static var previews: some View {
        LoggedInView(dismissView: **Binding<Bool>**)
    }
}
#endif

How would I go an initialize it? tried:

Binding<Bool>.init(false)
Binding<Bool>(false)

Or even:

@Binding var dismissView: Bool = false

But none worked... any ideas?

Answer

Paulw11 picture Paulw11 · Jun 20, 2019

When you use your LoggedInView in your app you do need to provide some binding, such as an @State from a previous view or an @EnvironmentObject.

For the special case of the PreviewProvider where you just need a fixed value you can use .constant(false)

E.g.

#if DEBUG
struct LoggedInView_Previews : PreviewProvider {
    static var previews: some View {
        LoggedInView(dismissView: .constant(false))
    }
}
#endif