Alternative to switch statement in SwiftUI ViewBuilder block?

前端 未结 6 1574
耶瑟儿~
耶瑟儿~ 2020-12-02 12:21

⚠️ 23 June 2020 Edit: From Xcode 12, both switch and if let statements will be supported in the ViewBuilder!

I’ve been trying to replicate an app of

6条回答
  •  悲&欢浪女
    2020-12-02 12:52

    For not using AnyView(). I will use a bunch of if statements and implement the protocols Equatable and CustomStringConvertible in my Enum for retrieving my associated values:

    var body: some View {
        ZStack {
            Color("background1")
                .edgesIgnoringSafeArea(.all)
                .onAppear { self.viewModel.send(event: .onAppear) }
            
            // You can use viewModel.state == .loading as well if your don't have 
            // associated values
            if viewModel.state.description == "loading" {
                LoadingContentView()
            } else if viewModel.state.description == "idle" {
                IdleContentView()
            } else if viewModel.state.description == "loaded" {
                LoadedContentView(list: viewModel.state.value as! [AnimeItem])
            } else if viewModel.state.description == "error" {
                ErrorContentView(error: viewModel.state.value as! Error)
            }
        }
    }
    

    And I will separate my views using a struct:

    struct ErrorContentView: View {
        var error: Error
    
        var body: some View {
            VStack {
                Image("error")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 100)
                Text(error.localizedDescription)
            }
        }
    }
    

提交回复
热议问题