Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Objective-C enum in Swift [duplicate]

Tags:

swift

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?

like image 561
Mitsuaki Ishimoto Avatar asked Aug 01 '14 10:08

Mitsuaki Ishimoto


1 Answers

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) } 
like image 88
Sulthan Avatar answered Sep 23 '22 23:09

Sulthan