Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"if not case" for enums in Swift [duplicate]

Tags:

swift

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 {
    // ...
}
like image 845
WetFish Avatar asked Oct 19 '22 04:10

WetFish


1 Answers

Equatable

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
}

Guard

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.

like image 164
Luca Angeletti Avatar answered Oct 21 '22 03:10

Luca Angeletti