5

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 {
    // ...
}
WetFish
  • 1,172
  • 2
  • 11
  • 21

1 Answers1

4

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.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • Thanks. I already implemented the "==" operator, but I didn't know I had to add ": Equatable". Seems redundant. – WetFish Aug 04 '16 at 22:29
  • It is not redundant as the compiler knows that you implement a protocol by explicitly declaring conformance. Otherwise it won't check if you have implemented the required methods. – Balázs Vincze Nov 27 '22 at 17:41