28
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Objective-CのenumをSwiftで使う

Last updated at Posted at 2014-09-22

(自分用メモ)

typedef enumで定義していたenumはそのままではSwiftでは使えない。

Interacting with C APIs

Objective-C
typedef enum {
    STATUS_IDLE,
    STATUS_CONNECTED,
    STATUS_DISCONNECTED
} STATUS;

NS_ENUMを使って書き換える。

Objective-C
typedef NS_ENUM(NSInteger, STATUS) {
    STATUS_IDLE,
    STATUS_CONNECTED,
    STATUS_DISCONNECTED
};

Swiftではこう変換される。

Swift
enum STATUS: Int {
    case IDLE
    case CONNECTED
    case DISCONNECTED
}

この時に各メンバの接頭辞が自動で省略されるので注意。おそらく列挙子の名前をメンバ名に対してマッチングして一致する部分+アンダースコア(あれば)までを省略していると思われる。

例えば、以下の場合、

Objective-C
typedef enum {
	WF_SENSOR_CONNECTION_STATUS_IDLE,
	WF_SENSOR_CONNECTION_STATUS_CONNECTING,
	WF_SENSOR_CONNECTION_STATUS_CONNECTED,
	WF_SENSOR_CONNECTION_STATUS_INTERRUPTED,
} WFSensorConnectionStatus_t;

NS_ENUMを使って以下のように書き換えると、

Objective-C
typedef NS_ENUM(NSInteger, WFSensorConnectionStatus_t) {
	WF_SENSOR_CONNECTION_STATUS_IDLE,
	WF_SENSOR_CONNECTION_STATUS_CONNECTING,
	WF_SENSOR_CONNECTION_STATUS_CONNECTED,
	WF_SENSOR_CONNECTION_STATUS_INTERRUPTED,
	WF_SENSOR_CONNECTION_STATUS_DISCONNECTING,	
};

Swiftからは以下のように見える。

Swift
enum WFSensorConnectionStatus_t {
    case SENSOR_CONNECTION_STATUS_IDLE
    case SENSOR_CONNECTION_STATUS_CONNECTING
    case SENSOR_CONNECTION_STATUS_CONNECTED
    case SENSOR_CONNECTION_STATUS_INTERRUPTED
    case SENSOR_CONNECTION_STATUS_DISCONNECTING
}

先頭のWF_の部分がアンダースコアを含めて省略されている。
要追加検証。

28
26
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
28
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?