SwiftUI 不喜欢 switch?

Rom*_*man 1 if-statement switch-statement swift swiftui

为了遵循这次讨论,我实施了Yurii Kotov的建议:

struct ContentView: View {

@State private var index = 0

@ViewBuilder
 var body: some View {
   if index == 0 {
       MainView()
   } else {
       LoginView()
   }
}
Run Code Online (Sandbox Code Playgroud)

效果很好。但如果我尝试使用 switch 语句来代替:

    switch  index {
        case 0: MainView()
        case 1: LoginView()
        default:
            print("# error in switch")
        }
Run Code Online (Sandbox Code Playgroud)

什么都没发生。没有错误警报,但也根本没有结果。有人可以帮忙吗?

Jac*_*sox 8

我对默认情况有一个问题,我希望“中断”类型的情况能够使切换变得详尽。SwiftUI 需要某种类型的视图,我发现

EmptyView()解决了这个问题。

这里还注意到EmptyView 讨论你“必须返回一些东西”

struct FigureListMenuItems: View {
    var showContextType: ShowContextEnum
    @Binding var isFavoriteSeries: Bool?

    var body: some View {
    
        Menu {
            switch showContextType {
            case .series:
                Button(action: { toggleFavoriteSeries() }) {
                    isFavoriteSeries! ?
                    Label("Favorite Series?", systemImage: "star.fill")
                        .foregroundColor(.yellow)
                    :
                    Label("Favorite Series?", systemImage: "star")
                        .foregroundColor(.yellow)
                }
            default: // <-- can use EmptyView() in this default too if you want
                Button(action: {}) {
                    Text("No menu items")
                }
            }
        } label: {
            switch showContextType {
            case .series:
                isFavoriteSeries! ?
                Image(systemName: "star.fill")
                    .foregroundColor(.yellow)
                :
                Image(systemName: "star")
                    .foregroundColor(.yellow)
            default:
                EmptyView()
            }
            Label("Menu", systemImage: "ellipsis.circle")
        }
    }

    private func toggleFavoriteSeries() {
        isFavoriteSeries?.toggle()
    }
}
Run Code Online (Sandbox Code Playgroud)

开关枚举

enum ShowContextEnum: Int {
    case series = 1
    case whatIsNew = 2
    case allFigures = 3
}
Run Code Online (Sandbox Code Playgroud)