5

Looks like Enumerations in Swift cannot be compared for equality. Here is the code I would expect to work:

let areEqual = MyEnum.SomeEnumValue == MyEnum.SomeEnumValue

However, this does not compile and throws error: Cannot invoke '==' with an argument list of type '(MyEnum, MyEnum)'.

Is it possible to compare 2 Enumeration values using == operator or do I really write switch-case for that?


EDIT

Here is self containing example. Just past it to playground and you should see the compilation error.

import UIKit

enum MyEnum {
    case SomeValue(Int)
    case OtherValue(Double)
    case ThirdValue
}

let areEqual = MyEnum.ThirdValue == MyEnum.ThirdValue

Looks a bit like Swift bug because it lets you compare Enumerations that has no associated values without complains. So I hope this is not expected behaviour (allowing to compare some Enumerations but not others).

Rasto
  • 17,204
  • 47
  • 154
  • 245
  • 2
    I cannot reproduce the problem. Can you show a (minimal) complete, self-contained example (including the enum definition) ? Also it is unclear (to me) if you want to compare enumeration constants or the values of variables. – Martin R Oct 04 '14 at 19:55
  • can you post your full code? – Steve Rosenberg Oct 04 '14 at 19:55
  • @Martin R Working on it. Just a moment. – Rasto Oct 04 '14 at 19:56
  • @MartinR why it is working for first case without intializer values – codester Oct 04 '14 at 20:09
  • @Martin MyEnum.Third is just as simple as it could possibly be. And I am only comparing that one. – Rasto Oct 04 '14 at 20:12
  • 1
    @drasto: `MyEnum.ThirdValue` is an expression of the type `MyEnum`, and as stated in the answers to the possible duplicate, `==` is not implemented for enumerations *with associated values*. You can file a bug report at Apple, but we cannot explain why the Swift people did not implement it. – Martin R Oct 04 '14 at 20:20

1 Answers1

0

This works for me:

enum CompassPoint {
    case North
    case South
    case East
    case West
}

let isEqual = CompassPoint.North ==  CompassPoint.South
//false

another example:

enum CompassPoint: Int {
    case North = 1, South, East, West
}

let isEqual = CompassPoint.North ==  CompassPoint.South
//false

this will work also:

enum MyEnum {
    case SomeValue
    case OtherValue
    case ThirdValue
}


let areEqual = MyEnum.ThirdValue == MyEnum.ThirdValue

but your example the enum has different types. You will only be able o compare various assigned to them.

Steve Rosenberg
  • 19,348
  • 7
  • 46
  • 53
  • Please see my edit for what is not working. Please consider deleting this answer as it address the problem stated in original question. – Rasto Oct 04 '14 at 20:08