SwiftUI 中的关联枚举状态

Associated enum state in SwiftUI

如何在 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")
        }
    }
}

编译器报错:

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

这里是固定变体。使用 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")
            }
        }
    }
}