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?
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With