Is there a way to invert case .A = enumValue
and make it something like 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...
I'm trying to remove the empty if-block and reduce the number of lines, so I'm not looking for something like
var condition1 = true
if case .A = enumValue {
condition1 = false
}
if condition1 {
// ...
}
First of all you need to make you enum 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
}
Now your scenario is a perfect fit tor the Guard
statement
func foo() {
guard enumValue != .A else { return }
if otherValue == "something" {
// Do stuff...
} else {
// Do other stuff...
}
}
In the code above, if enumValue != .A
then the code flow does continue.
Otherwise (when enumValue == .A
) the execution stops and { return }
is executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With