SwiftUI switch function without AnyView

I learned that I shouldn’t be using AnyView() in SwiftUI. I have written many functions with switch statements to return corresponding Views like the below code. I’m trying to learn the best way to migrate the switch statements away from AnyView()

struct T01: View{
    var body: some View{
        VStack{
            showView(i: 1)
        }
    }
    
    func showView(i: Int) -> some View{
        switch(i){
            case 0: return AnyView(viewOne)
            case 1: return AnyView(viewTwo)
            default: return AnyView(EmptyView())
        }
    }
    
    var viewOne: some View {
        Text("View One")
    }
    
    var viewTwo: some View {
        Text("View Two")
    }
}

Thanks for any help!!!

>Solution :

Your showView function has to return the same type of view each time, which is why AnyView works.

You have a couple of options to fix this:

Wrap everything in another View, e.g. a Group

Group {
    switch  i {
    case 0:
        viewOne
    case 1:
        viewTwo
    default:
        EmptyView()
    }
}

Mark the function with the @ViewBuilder attribute

@ViewBuilder
func showView(i: Int) -> some View {
    switch  i {
    case 0:
        viewOne
    case 1:
        viewTwo
    default:
        EmptyView()
    }
}

Leave a Reply