如何使用关联的枚举作为 @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/