枚举是一种常量命名方式,可以被我们应用来表示状态机的状态,传递给方法的选项以及状态码等值。
// 示例
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。实现枚举所用的数据类型取决于编译器。
// 自己指定底层数据类型,不使用编译器所分配的序号 示例
enum EOCConnectionStateConnectionState : NSInteger {
EOConnectionStateDisConnected = 1,
EOConnectionStateConnecting,
EOConnectionStateConnected,
};
typedef enum EOCConnectionStateConnectionState EOCConnectionStateConnectionState;
// 定义枚举变量
EOCConnectionStateConnectionState state = EOConnectionStateConnected;
说明:
代码中“enum EOCConnectionStateConnectionState : NSInteger”指定了底层数据类型是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框架中定义了一些辅助的宏,用这宏来定义枚举类型时,也可以指定保存枚举值的底层数据类型。
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语句中使用,不要实现default分支。这样,加入新枚举后,编译器就会提示开发者,switch语句并未处理所有枚举。
EOConnectionState state = EOConnectionStateConnecting;
switch (state) {
case EOConnectionStateDisConnected:
break;
case EOConnectionStateConnecting:
break;
case EOConnectionStateConnected:
break;
}