枚举只是一种常量命名方式,入下列枚举表示链接状态
enum EOCConnectionState:NSInteger{ EOCConnectionStateDisconnected = 1, EOCConnectionStateConnecting, EOCConnectionStateConnected,};编译器会为每一个枚举分配一个独有的编号,从0开始,然而定义没巨变量的方式却不太简洁,如下enum EOCConnectionState state = EOCConnectionStateConnected;另一种方式
enum EOCConnectionState{ EOCConnectionStateDisconnected, EOCConnectionStateConnecting, EOCConnectionStateConnected,};typedef enum EOCConnectionState EOCConnectionState;这样使用会简洁一些EOCConnectionState state = EOCConnectionStateConnected;c++11标准修订类枚举的某些特性,其中一项就是可以指明用何种“底层数据类型”来保存枚举类型的变量。这样的好处是,可以向前申明枚举变量。如下enum EOCConnectionState:NSInteger{ EOCConnectionStateDisconnected = 1, EOCConnectionStateConnecting, EOCConnectionStateConnected,};上述代码把EOCConnectionStateDisconnected的值设为1而不是默认分配的0.
还有一种情况应该使用枚举类型,那就是定义选项的时候,若这些选项可以彼此组合,则更应该如此,和选项之久可以通过“按位或操作符”来组合,例如
enum UIViewAutoresizing{ UIViewAutoresizingNone = 0, UIViewAutoresizingFlexibleLeftMargin = 1 << 0, UIViewAutoresizingFlexibleWidth = 1 << 1, UIViewAutoresizingFlexibleRightMargin = 1 << 2, UIViewAutoresizingFlexibleTopMargin = 1 << 3, UIViewAutoresizingFlexibleHeight = 1 << 4, UIViewAutoresizingFlexibleBottomMargin = 1 << 5};Foundation框架中定义了一写辅助的宏,用这些宏来定义枚举类型时,也可以指定用于保存枚举值的底层数据类型,这些宏具有向后兼容能力
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};typedef NS_ENUM(NSUInteger, UIViewAutoresizing) { EOCConnectionStateDisconnected , EOCConnectionStateConnecting, EOCConnectionStateConnected,};从枚举定义来看,NS_ENUM和NS_OPTIONS本质是一样的,仅仅从字面上来区分其用途。NS_ENUM是通用情况,NS_OPTIONS一般用来定义具有位移操作或特点的情况。注:我们总习惯在switch语句中加上default分支,然而,若是枚举来定义状态机,最好不要有default分支,这样的话,如果稍后又加了一种状态,那么编译器就会发出浸膏信息,提示新加入的状态并未在switch分支中处理
新闻热点
疑难解答