Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!!!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading