Condition in NavigationLink Destination

Hello, Is there a way to use "switch statement" inside of a NavigationLink Destination?

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
Answered by OOPer in 667621022
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:
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()
}
}
}


Accepted Answer
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:
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()
}
}
}


Condition in NavigationLink Destination
 
 
Q