SwiftからObjective-CのEnumを利用することはできますが、
微妙にObjective-Cの頃とは使い方が変わっているのでそのままでは使えません。
例えばこんな適当なEnum型をObjective-C側に書きます。
objective-C
typedef NS_ENUM(NSInteger, APIState) {
APIStateSuccess = 0,
APIStateFailure = 1,
APIStateUnknown = 0xff
};
それをSwift側でそのままSwitch文に使おうとこんな感じに書いてしまうと・・・
swift-error
let state = 1;
switch state {
case APIState.Success:
break
case APIState.Failure:
break;
default:
break;
}
以下のどちらかのようなエラーが出てくると思います。
Enum case 'APIState' is not a member of type 'Int'
Cannot convert value of type 'APIState' to expected argument type 'Int'
Int値を使うときは、rawValueプロパティを利用しましょう。
swift-error
let state = 1;
switch state {
case APIState.Success.rawValue:
break
case APIState.Failure.rawValue:
break;
default:
break;
}
この場合、逆にInt値からEnum型に変換することもできます。
var type1 = APIState(rawValue: 0)
var type2 = APIState(rawValue: 1)
var type3 = APIState(rawValue: 2) // 変換できなければnil