swift - SwiftUI 中的关联枚举状态

标签 swift enums swiftui associated-value

如何使用关联的枚举作为 @State if 中的变量SwiftUI 中的声明?

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")
        }
    }
}

编译器报这个错误:

Protocol 'Equatable' requires that 'ProfileView.Choice' conform to 'Equatable'

最佳答案

您需要使用 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)
}

关于swift - SwiftUI 中的关联枚举状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62173525/

相关文章:

SwiftUI - 类型 '[Color]' 的值没有成员 'identified'

ios - 将 .swift 文件导入 Objective-C 文件会导致方法声明错误缺少上下文

swift - Guard let 构造,仍然出现 fatal error : Index out of range

json - swift 4.2 : Type 'T' does not conform to protocol 'Decodable'

c# - 如何从枚举中获取字符串值

Swift:其中包含特殊字符(如 .)的枚举名称

c++ - C++ 枚举中的最大值和最小值

ios - SwiftUI:NavigationView/NavigationLink:启动并推送目的地?

ios - 暂停/播放 AVPlayer 时出现问题

swift - 如何停止所有 SWIFTUI 按钮一起切换?