枚舉是一種常量命名方式,可以被我們應用來表示狀態(tài)機的狀態(tài),傳遞給方法的選項以及狀態(tài)碼等值。
// 示例
enum EOCConnectionState {
EOConnectionStateDisConnected,
EOConnectionStateConnecting,
EOConnectionStateConnected,
};
// 定義枚舉變量 示例
enum EOCConnectionState state = EOConnectionStateConnected;
每次定義枚舉變量還需要寫“enum”,不簡潔。
可以使用typedef關鍵字重新定義枚舉類型
enum EOCConnectionState {
EOConnectionStateDisConnected,
EOConnectionStateConnecting,
EOConnectionStateConnected,
};
typedef enum EOCConnectionState EOCConnectionState;
// 定義枚舉變量 示例
EOCConnectionState state = EOConnectionStateConnected;
上面的枚舉示例,編譯器會為枚舉分配一個獨有的編號,從0開始,每個枚舉遞增1。實現(xiàn)枚舉所用的數(shù)據(jù)類型取決于編譯器。
// 自己指定底層數(shù)據(jù)類型,不使用編譯器所分配的序號 示例
enum EOCConnectionStateConnectionState : NSInteger {
EOConnectionStateDisConnected = 1,
EOConnectionStateConnecting,
EOConnectionStateConnected,
};
typedef enum EOCConnectionStateConnectionState EOCConnectionStateConnectionState;
// 定義枚舉變量
EOCConnectionStateConnectionState state = EOConnectionStateConnected;
說明:
代碼中“enum EOCConnectionStateConnectionState : NSInteger”指定了底層數(shù)據(jù)類型是NSInteger。
把EOConnectionStateDisConnected的值設為1,而不使用編譯器所分配的0,所以接下來幾個枚舉的值都會在上一個的基礎上遞增1。
枚舉定義選項的時候,選項還可以彼此組合,各選項之間可通過“按位或操作符”來組合。
// 要進行按位或操作符的枚舉 示例
enum UIViewAutoresizingEnum {
UIViewAutoresizingSNone = 0,
UIViewAutoresizingSFlexibleLeftMargin = 1 << 0,
UIViewAutoresizingSFlexibleWidth = 1 << 1,
UIViewAutoresizingSFlexibleRightMargin = 1 << 2,
UIViewAutoresizingSFlexibleTopMargin = 1 << 3,
UIViewAutoresizingSFlexibleHeight = 1 << 4,
UIViewAutoresizingSFlexibleBottomMargin = 1 << 5
};
typedef enum UIViewAutoresizingEnum UIViewAutoresizingEnum;
// 定義枚舉變量
UIViewAutoresizingEnum resize = UIViewAutoresizingSFlexibleWidth | UIViewAutoresizingSFlexibleHeight;
Foundation框架中定義了一些輔助的宏,用這宏來定義枚舉類型時,也可以指定保存枚舉值的底層數(shù)據(jù)類型。
typedef NS_ENUM(NSUInteger, EOConnectionState)
{
EOConnectionStateDisConnected,
EOConnectionStateConnecting,
EOConnectionStateConnected,
};
typedef NS_OPTIONS(NSUInteger, EOCPermittedDirection)
{
EOCPermittedDirectionUp = 1 << 0,
EOCPermittedDirectionDown = 1 << 1,
EOCPermittedDirectionLeft = 1 << 2,
EOCPermittedDirectionRight = 1 << 3,
};
說明:
需要以按位或操作來組合的枚舉,應使用NS_OPTIONS定義。
不需要相互組合,應使用NS_ENUM來定義。
枚舉在switch語句中使用,不要實現(xiàn)default分支。這樣,加入新枚舉后,編譯器就會提示開發(fā)者,switch語句并未處理所有枚舉。
EOConnectionState state = EOConnectionStateConnecting;
switch (state) {
case EOConnectionStateDisConnected:
break;
case EOConnectionStateConnecting:
break;
case EOConnectionStateConnected:
break;
}