Navigating programmatically in SwiftUI

I followed the official SwiftUI tutorial to learn how to use SwiftUI. In my app, I want to build login functionality. For that, I have a login screen with a button. On pressing it, a request is sent out and only after receiving the response, I want to navigate to the next screen. The same principle is needed for logging out. After searching the web, the following approach is suggested on many pages, where a state variable is changed by the button action to trigger the empty navigation event.

Code Block swift
@State var selection: Int? = nil
...
Button("Login", action: {
        viewModel.login(name: username, password: password) { didSucceed in
          if didSucceed {
            self.selection = 1
          } else {
            print("Login error, TODO: proper handling")
          }
        }
      })
NavigationLink(destination: MapScreen(), tag: 1, selection: $selection) { EmptyView() }
        .hidden()


Is this the officially recommended way of navigating programmatically in SwiftUI or does a more convenient way exist?
Hi there,
in this instance I would consider this to be a very adequate solution. It of course gets more complicated when you need multiple NavigationLinks, but as long as you only use a few this a reliable and simple solution. You could even remove the .hidden() modifier and just wrap the Link in an HStack.

Take care
David
Navigating programmatically in SwiftUI
 
 
Q