[英]Compare Swift enum regardless of the associated value
Is it somehow possible to test an enum case regardless of the associated value ? 无论相关值如何,是否可以以某种方式测试枚举案例?
enum Abc {
case A(a:Int)
case B(b:Int)
}
let a = Abc.A(a:1)
a == Abc.A // <= Not possible
Sure, you can do this in a switch
: 当然,你可以在一个
switch
做到这一点:
switch a {
case .A:
print("it's A")
default:
print("it's not A")
}
Or use pattern matching in an if
statement: 或者在
if
语句中使用模式匹配:
if case .A = a {
print("it's A")
} else {
print("it's not A")
}
If you're still interested in the associated value after matching the case, you can extract it like so: 如果在匹配大小写后仍然对相关值感兴趣,可以像这样提取它:
switch a {
case .A(let value):
...
}
if case .A(let value) = a {
...
}
Note @overactor's comment below that you can also write this as case let .A(value)
– it's mainly a matter of personal preference. 请注意@ overactor在下面的评论 ,您也可以将其写为
case let .A(value)
- 这主要case let .A(value)
个人偏好。
You can use an if case
您可以使用
if case
enum ABC {
case A(a: Int)
case B(b: Int)
}
let a = ABC.A(a: 1)
if case .A = a {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.