swift - Swift 模式匹配 - 保护中的多个枚举大小写模式?
问题描述
使用枚举案例和守卫以允许多个案例继续进行的正确语法是什么?
通过 aswitch
我们可以使用case-item-list来组合 switch case。
有没有类似的 for guard
or if
statements?
这是我想做的有点像的代码示例...
enum Thingy {
case one
case two
case three
}
func doSomething(with value: Thingy) {
switch value {
case .one, .three:
print("I like these numbers")
default:
print("Two")
}
}
// Doesn't compile
func doSomethingAlt(with value: Thingy) {
guard .one, .three = value else {
print("Two")
return
}
print("I like these numbers")
}
解决方案
您只需要给出由OR
( ||
) 条件分隔的条件。方法如下:
func doSomethingAlt(with value: Thingy) {
guard value == .one || value == .three else {
print("Two")
return
}
print("I like these numbers")
}
这将要求enum
符合Equatable
. Enums
没有关联值或raw-type
自动符合Equatable
. 由于Swift 4.1
即使具有关联类型的枚举案例也会自动符合Equatable
. 这是一些代码:
enum Thingy: Equatable {
case one(String)
case two
case three
}
func doSomethingAlt(with value: Thingy) {
guard value == .one("") || value == .three else {
print("Two")
return
}
print("I like these numbers")
}
而且,由于Swift 5.1
枚举关联类型可以具有默认值。这是一个很棒的功能,所以你只需要这样做:
enum Thingy: Equatable {
case one(String = "")
case two
case three
}
func doSomethingAlt(with value: Thingy) {
guard value == .one() || value == .three else {
print("Two")
return
}
print("I like these numbers")
}
推荐阅读
- react-native - 如何使用 react-navigation 在选项卡导航器中重置其他堆栈导航器
- chef-infra - Mixlib::ShellOut::ShellCommandFailed:预期进程以 [0] 退出,但收到“-1”
- java - 启动缓慢 - Eclipse e4
- tensorflow - tflite uint8 量化模型输入输出浮点转换
- powershell - 使用 powershell 从 web.config 中提取 dbname
- python - 如何阻止 seaborn kdeplots 调整图像大小而不产生锐利的截断?
- google-apps-script - 是否有 ImportRange 的工作版本作为脚本?
- android - 使用接口类从另一个活动刷新 ListView 但适配器导致空对象问题
- c++ - C ++赋值与已删除的赋值运算符一起使用?
- python - 可以将字符串转换为命名变量或替代变量吗?