【问题标题】:Associated enum state in SwiftUISwiftUI 中的关联枚举状态
【发布时间】:2020-06-03 13:03:45
【问题描述】:

如何在 SwiftUI 的 if 语句中使用关联的枚举作为 @State 变量?

struct ProfileView: View {
    @State private var choice = Choice.simple

    private enum Choice {
        case simple
        case associated(Int)
    }

    var body: some View {
        if choice == .simple {
            Text("Simple")
        }
    }
}

编译器报这个错误:

协议“Equatable”要求“ProfileView.Choice”符合“Equatable”

【问题讨论】:

  • 根本问题出在我的生产代码中,我使用的是结构体(与重现中的 Int 相比),而结构体没有实现 Equatable。然后在简化的重现中,我没有确保总是有一个根视图,这恰好给出了同样的错误。这让我认为问题与@State 的实现方式有关。

标签: swift enums swiftui associated-value


【解决方案1】:

您需要使用if case 来检查enum 变量是否与某个case 匹配。

var body: some View {
    if case .simple = choice {
        return Text("Simple")
    } else {
        return Text("Not so simple")
    }
}

如果您确实想使用关联的值来显示,我建议使用switch 来覆盖所有enum 情况。

var body: some View {
    let text: String
    switch choice {
    case .simple:
        text = "Simple"
    case .associated(let value):
        text = "\(value)"
    }
    return Text(text)
}

【讨论】:

    【解决方案2】:

    这是固定的变体。使用 Xcode 11.4 测试。

    struct ProfileView: View {
        @State private var choice = Choice.simple
    
        private enum Choice: Equatable {
            case simple
            case associated(Int)
        }
    
        var body: some View {
            Group {
                if choice == .simple {
                    Text("Simple")
                } else {
                    Text("Other")
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多