49

I have 2 enum definition in Objective-C file and Swift file.

Japanese.h

typedef enum {
  JapaneseFoodType_Sushi = 1,
  JapaneseFoodType_Tempura = 2,
} JapaneseFoodType;

US.swift

enum USFoodType {
  case HUMBERGER;
  case STEAK;
}

as we know, I can use Objective-C enum like following;

Japanese.m

- (void)method {
  JapaneseFoodType type1 = JapaneseFoodType_Sushi;
  JapaneseFoodType type2 = JapaneseFoodType_Tempura;
  if (type1 == type2) {// this is no problem
  }
}

But I can not use Objective-C enum in Swift file like following;

  func method() {
    var type1: USFoodType = USFoodType.HUMBERGER// no problem
    var type2: USFoodType = USFoodType.HUMBERGER// no problem
    if type1 == type2 {

    }

    var type3: JapaneseFoodType = JapaneseFoodType_Sushi// no problem
    var type4: JapaneseFoodType = JapaneseFoodType_Tempura// no problem
    if type3 == type4 {// 'JapaneseFoodType' is not convertible to 'Selector'

    }
  }

Is this a bug of Swift? And how can I use Objective-C (C) enum in Swift file?

Mitsuaki Ishimoto
  • 3,162
  • 2
  • 25
  • 32

2 Answers2

78

I think this is a bug because Swift should define == for C enums or an "to Int" conversion but it doesn't.

The simplest workaround is redefining your C enum as:

typedef NS_ENUM(NSUInteger, JapaneseFoodType) {
    JapaneseFoodType_Sushi = 1,
    JapaneseFoodType_Tempura = 2,
};

which will allow LLVM to process the enum and convert it to a Swift enum (NS_ENUM also improves your Obj-C code!).

Another option is to define the equality using reinterpret hack:

public func ==(lhs: JapaneseFoodType, rhs: JapaneseFoodType) -> Bool {
    var leftValue: UInt32 = reinterpretCast(lhs)
    var rightValue: UInt32 = reinterpretCast(rhs)

    return (leftValue == rightValue)
}
Sulthan
  • 128,090
  • 22
  • 218
  • 270
24

You should use NS_ENUM macro to make your enums Swift-compatible.

Also note that your enum literals should be accessed like JapaneseFoodType._Sushi, so it's probably a good idea to remove the underscore.

Nikolay Kasyanov
  • 897
  • 5
  • 14