4

I would like to compare an enum value to an enum type without using switch. The following code, for example, works using the ~= operator:

enum MyEnum {
    case A, B
}

let myEnum = MyEnum.A

let isA = myEnum ~= MyEnum.A

isA equals true above.

However, when I try to compare an enum of an enum type with an associated value, like below, I get the compile error Binary operator '~=' cannot be applied to two MyEnum operands.

enum MyEnum {
    case A, B(object: Any)
}

let myEnum = MyEnum.A

let isA = myEnum ~= MyEnum.A

Is there a way to work around this error to use the ~= pattern matching operator? Or is my only recourse the following syntax, which in my opinion is significantly more cumbersome:

enum MyEnum {
    case A, B(object: Any)
}

let myEnum = MyEnum.A

let isA: Bool
switch myEnum {
case .A:
    isA = true
default:
    isA = false
}

Thanks in advance for your input and suggestions!

Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
Ilias Karim
  • 4,798
  • 3
  • 38
  • 60

1 Answers1

3

From the documentation for Swift 1.2 "Enumeration case patterns appear only in switch statement case labels". So yes, you need to define your ~= operator (as from the answer pointed in the comments).

In case you just need isA and isB you can implement them using switch combined with _. In your case ~= couldn't work out of the box anyway, since you use an Any associated type, which is not Equatable (i.e.: how can I say if two .B(any) are equal since I cannot say if two any are equal?)

As an example, here is an implementation of from your code that uses String as the associated type. In case you just need the isA and isB, you can still use Any as the associated type without implementing the ~= operator.

enum MyEnum {
    case A, B(object: String)
}

let myEnumA = MyEnum.A
let myEnumB = MyEnum.B(object: "Foo")


func ~=(lhs: MyEnum, rhs: MyEnum) -> Bool {
    switch (lhs, rhs) {
    case (.A, .A):
        return true
    case let (.B(left), .B(right)):
        return left == right
    default:
        return false
    }
}

myEnumA ~= .A   // true
myEnumB ~= .B(object: "Foo") // true
myEnumB ~= .B(object: "Bar") // false

func isA(value: MyEnum) -> Bool {
    switch value {
    case .A:
        return true
    default:
        return false
    }
}

func isB(value: MyEnum) -> Bool {
    switch value {
    case .B(_):     // Ignore the associated value
        return true
    default:
        return false
    }
}
Matteo Piombo
  • 6,688
  • 2
  • 25
  • 25