在用一系列常量來表示錯(cuò)誤狀態(tài)碼或可組合的選項(xiàng)時(shí),很適合 枚舉 為其命名。
枚舉是一種常量命名方式,某個(gè)對(duì)象所經(jīng)歷的各種狀態(tài)就可以定義為一個(gè)簡(jiǎn)單的枚舉集(enumeration set)。例如:
enum EOCConnectionState {
EOCConnectionStateDisconnected,
EOCConnectionStateConnecting,
EOCConnectionStateConnected,
};
編譯器會(huì)為每個(gè)枚舉值分配一個(gè)獨(dú)有的編號(hào),從0開始,依次加1。一個(gè)字節(jié)最多可表示0~255共256種(2^8)枚舉變量。
定義枚舉變量:
enum EOCConnectionState state = EOCConnectionStateDisconnected;
為簡(jiǎn)便起見,可以使用 typedef 關(guān)鍵字重新定義枚舉類型:
enum EOCConnectionState {
EOCConnectionStateDisconnected,
EOCConnectionStateConnecting,
EOCConnectionStateConnected,
};
typedef enum EOCConnectionState EOCConnectionState;
現(xiàn)在就可以不寫 enum,直接定義了:
EOCConnectionState state = EOCConnectionStateDisconnected;
- 指定“底層數(shù)據(jù)類型”(underlying type)(C++11標(biāo)準(zhǔn))的語法:
enum EOCConnectionState : NSInteger {
/*...*/
}
- 指定分配的序號(hào):
enum EOCConnectionState {
EOCConnectionStateDisconnected = 1,
EOCConnectionStateConnecting, //接下來的值會(huì)依次遞增1
EOCConnectionStateConnected
};
- 若定義的枚舉選項(xiàng)可以彼此組合,則更應(yīng)如此。例如:
// UIView.h
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
UIViewAutoresizingNone = 0,
UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizingFlexibleWidth = 1 << 1,
UIViewAutoresizingFlexibleRightMargin = 1 << 2,
UIViewAutoresizingFlexibleTopMargin = 1 << 3,
UIViewAutoresizingFlexibleHeight = 1 << 4,
UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
其二進(jìn)制值如圖所示:

二進(jìn)制值示意圖
- 此外,枚舉用法也可用于
switch語句中,例如:
typedef NS_ENUM(NSUInteger, EOCConnectionState) {
EOCConnectionStateDisconnected,
EOCConnectionStateConnecting,
EOCConnectionStateConnected
};
switch (_currentState) {
EOCConnectionStateDisconnected:
//...
break;
EOCConnectionStateConnecting:
//...
break;
EOCConnectionStateConnected:
//...
break;
}
注:若用枚舉來定義狀態(tài)機(jī)(state machine),最好不要有
default分支。