有没有办法反转case .A = enumValue并使其类似enumValue != .A?
enum MyEnum {
case A
case B
case C
case D(something: OtherEnum)
}
let enumValue: MyEnum = ...
let otherValue: String = ...
if case .A = enumValue {
// Do nothing
} else {
if otherValue == "something" {
// Do stuff...
} else {
// Do other stuff...
}
}
// More code...
Run Code Online (Sandbox Code Playgroud)
我正在尝试删除空的 if 块并减少行数,所以我不是在寻找类似的东西
var condition1 = true
if case .A = enumValue {
condition1 = false
}
if condition1 {
// ...
}
Run Code Online (Sandbox Code Playgroud)
首先你需要进行枚举Equatable
enum MyEnum: Equatable {
case A
case B
case C
case D(something: OtherEnum)
}
func ==(left:MyEnum, right:MyEnum) -> Bool {
return true // replace this with your own logic
}
Run Code Online (Sandbox Code Playgroud)
现在您的场景非常适合该Guard声明
func foo() {
guard enumValue != .A else { return }
if otherValue == "something" {
// Do stuff...
} else {
// Do other stuff...
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,如果enumValue != .Athen 代码流程确实继续。否则(当enumValue == .A)执行停止并被{ return }执行。
| 归档时间: |
|
| 查看次数: |
1523 次 |
| 最近记录: |