Attention! Translated article might be found on my English blog.

2014年11月8日土曜日

ObjCとSwiftで共通のenumを使う場合はObjC側にenumを書く

ObjC側からSwiftのenumは使えないようです。
参考: objective c - Is it possible to use Swift's Enum in Obj-C? - Stack Overflow

よってSwift側からObjCのenumを参照します。
共用する場合、ObjC側ではtypedef enumの代わりにNS_ENUMまたはNS_OPTIONSを使って宣言する必要があるようです。
参考: SwiftからObjective-Cのenumを扱う時の注意事項2 - tomoyaonishiのブログ

例えば、以下のようなenumの場合、

typedef enum TRRPlayerDirection {
    kTRRPlayerDirection_Right,
    kTRRPlayerDirection_Left

} TRRPlayerDirection;

NS_ENUMを使い、

NS_ENUM(NSInteger, TRRPlayerDirection) {
    kTRRPlayerDirection_Right,
    kTRRPlayerDirection_Left

};

と修正する必要があります。

Swift側ではenum名の'TRRPlayerDirection'以外にも接頭辞のkとアンダースコアを除外するのか、
TRRPlayerDirection.RightおよびTRRPlayerDirection.Leftという記述でenum要素を参照することができます。