作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
无论关联值如何,是否有可能以某种方式测试枚举案例?
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/
我是一名优秀的程序员,十分优秀!