0

I'm building programmatic navigation in SwiftUI app. I want to open screens when model changes, not when user just taps on button. I want to keep my code descriptive without unnecessary optionals all over it. Problem is some SwiftUI methods expect to see Binding<Bool?> instead of more descriptive Binding<Bool>. Example:

class NavigationState: ObservableObject {
    @Published var showNextScreen: Bool = false
}

struct FirstView: View {
    @EnvironmentObject var navigationState: NavigationState

    var body: some View {
        NavigationLink("Show next screen",
                       destination: NextView(),
                       tag: true,
                       selection: $navigationState.showNextScreen)  // <--- Error: Cannot convert value of type 'Binding<Bool>' to expected argument type 'Binding<Bool?>'
    }
}

Is there a way to build programmatic navigation without making ivar optionals all over the app by changing @Published var showNextScreen: Bool = false to @Published var showNextScreen: Bool? = false Because changing it to optional will make code less descriptive than it should be.

1 Answers1

0

There is an initialiser that converts a Binding<V> to a Binding<V?>, so you just need to do:

NavigationLink("Show next screen",
               destination: NextView(),
               tag: true,
               selection: Binding($navigationState.showNextScreen))

Somewhat relatedly, using another initialiser, you can also convert a Binding<V?> to a Binding<V>? (answer by me).

Sweeper
  • 213,210
  • 22
  • 193
  • 313