无论关联的值如何,是否可以以某种方式测试枚举案例?

enum Abc {
    case A(a:Int)
    case B(b:Int)
}

let a = Abc.A(a:1)

a == Abc.A  // <= Not possible

最佳答案

当然,您可以在 switch 中执行此操作:

switch a {
case .A:
    print("it's A")
default:
    print("it's not A")
}

或者在 if 语句中使用模式匹配:
if case .A = a {
    print("it's A")
} else {
    print("it's not A")
}

如果您在匹配大小写后仍然对关联值感兴趣,您可以像这样提取它:
switch a {
case .A(let value):
    ...
}
if case .A(let value) = a {
    ...
}

注意@overactor's comment below,你也可以把它写成case let .A(value)——这主要是个人喜好的问题。

关于swift - 无论关联值如何,都比较 Swift 枚举,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37808161/

10-12 00:18
查看更多