如果模式匹配多个案例怎么办? [英] How to do if pattern matching with multiple cases?
问题描述
我正在寻找在 if case 语句中对多个 case 进行模式匹配的语法.示例如下:
I'm searching for the syntax to do pattern matching with multiple cases in an if case statement. The example would be this:
enum Gender {
case Male, Female, Transgender
}
let a = Gender.Male
现在我想检查一下,a 是 .Male 还是 .Female.但我想避免为此使用 switch.但是 switch 语句会是这样的:
Now I want to check, if a is .Male OR .Female. But I would like to avoid using switch for this. However the switch statement would be like this:
switch a {
case .Male, .Female:
// do something
}
可以用 if case 写这个吗?我会期待这个,但它没有用:(
Is it possible to write this with if case? I would expect this, but it didn't work :(
if case .Male, .Female = a {
}
推荐答案
一个简单的数组就能解决问题:
A simple array does the trick:
if [.Male, .Female].contains(a) {
print("Male or female")
} else {
print("Transgender")
}
我只是对 Swift 推断类型的能力感到惊讶.在这里,它得到 .Male
和 .Female
是来自 a
的性别类型.
I'm simply amazed at Swift's ability to infer type. Here, it gets that .Male
and .Female
are of type gender from a
.
这篇关于如果模式匹配多个案例怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!