Hello, Is there a way to use "switch statement" inside of a NavigationLink Destination?
Example:
(The views are different, that's why I don't put them in one struct)
Thank you
Example:
Code Block NavigationLink(destination: switch i { case 0: MatematicaView() case 1: ArteView() default: EmptyView() }){ Text("Hello") }
(The views are different, that's why I don't put them in one struct)
Thank you
The destination of NavigationLink needs to be an expression returning a View.
Unfortunately, switch statement is not an expression in Swift.
You may need to use the ternary operator nested with AnyView:
Or define a function returning a View and use it:
Unfortunately, switch statement is not an expression in Swift.
You may need to use the ternary operator nested with AnyView:
Code Block NavigationLink(destination: i == 0 ? AnyView(MatematicaView()) : i == 1 ? AnyView(ArteView()) : AnyView(EmptyView()) ){ Text("Hello") }
Or define a function returning a View and use it:
Code Block struct ContentView: View { @State var i = 0 var body: some View { NavigationView { NavigationLink(destination: chooseDestination() ){ Text("Hello") } //... } } @ViewBuilder func chooseDestination() -> some View { switch i { case 0: MatematicaView() case 1: ArteView() default: EmptyView() } } }