0

I have a list of Menu

let muscleEtfs = Menu(name:"MuscleETFs",  image:"image", destination: .muscleETFs)

let menus: [Menu] = [home, marketTrend, indexes, sectors, stockAnalysis, backtest, screener, myPortfolio, watchList, muscleStocks, muscleEtfs]

My goal is to change the destination of NavigationLink in SwiftUI conditionally. Could anybody explain to me why the switch case does not work but if does.

let muscleEtfs = Menu(name:"MuscleETFs",  image:"image", destination: .muscleETFs)

    var body: some View {
        let menus: [Menu] = [home, marketTrend, indexes, sectors, stockAnalysis, backtest, screener, myPortfolio, watchList, muscleStocks, muscleEtfs]

        return List {
            ForEach(menus) { menu in

                // This does not work
                switch menu.destination {
                case .news:
                    NavigationLink(
                            destination: HomeNewsView(menu: menu)
                    )
                    {
                        Text("\(menu.name)")
                    }
                default:
                    NavigationLink(
                            destination: HomeNewsView(menu: menu)
                    )
                    {
                        Text("\(menu.name)")
                    }

                }

                // This does
                if menu.destination == .news   {
                    NavigationLink(
                            destination: HomeNewsView(menu: menu)
                    )
                    {
                        Text("\(menu.name)")
                    }
                }
            }
        }

Using switch conditions throws compile error on Xcode

Closure containing control flow statement cannot be used with function builder 'ViewBuilder'

Nafiz
  • 462
  • 4
  • 17
  • switches returning Views are not implemented the way you want it. You can use the logic inside a method or use if/else only. – Fabian Dec 23 '19 at 08:03
  • 2
    Does this answer your question? [Alternative to switch statement in SwiftUI ViewBuilder block?](https://stackoverflow.com/questions/56736466/alternative-to-switch-statement-in-swiftui-viewbuilder-block) – nayem Dec 23 '19 at 08:04
  • Thanks. only this would work not View or AnyView only some view as a return type. – Nafiz Dec 23 '19 at 08:29

1 Answers1

0

This works, remember return type AnyView or View won't work.

func destinationView(menu: Menu) -> some View {

        switch menu.destination {
        case .news:
            return NavigationLink(
                    destination: HomeNewsView(menu: menu)
            )
            {
                Text("\(menu.name)")
            }
        default:
            return NavigationLink(
                    destination: HomeNewsView(menu: menu)
            )
            {
                Text("\(menu.name)")
            }
        }

    }
Nafiz
  • 462
  • 4
  • 17