LoginSignup
2
2

More than 5 years have passed since last update.

SwiftからObjective-Cのenum型を使うときの注意メモ

Last updated at Posted at 2016-07-13

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
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2