Objective-C枚举

2017-10-30  本文已影响11人  14cat

枚举类型

enum Direction {up, down, left, right};
enum Direction : UNSInteger {up, down, left, right};
// up=1,down=2,left=3,right=4
enum Direction {up = 1, down, left, right};

// 定义匿名枚举类型,并定义两个枚举变量
enum {male, female} me, you;
// 使用关键字typedef定义枚举类型
enum Direction {up, down, left, right} ;
typedef enum Direction Direction;

// 使用Direction代替完整的enum Direction
Direction var1, var2;

基础使用方法:

typedef enum _State {
  StateOK = 0,
  StateError,
  StateUnknow
} State;

// 指明枚举类型
State status = StateOK;

- (void)dealWithState:(State)state {
  switch(state) {
    case StateOK:
        break;
    case StateError:
        break;
    case StateUnknow:
        break;
  } 
}
enum Direction {
   up = 1 << 0, 
   down = 1 << 1, 
   left = 1 << 2, 
   right = 1 << 3
};

选项使用方法

//方向,可同时支持一个或多个方向
typedef enum _Direction {
    DirectionNone = 0,
    DirectionTop = 1 << 0        // 0001
    DirectionLeft = 1 << 1,      // 0010
    DirectionRight = 1 << 2,     // 0100
    DirectionBottom = 1 << 3     // 1000
} Direction;

//用“或”运算同时赋值多个选项
Direction direction = DirectionTop | DirectionLeft | DirectionBottom;  // 1011
//用“与”运算取出对应位
if (direction & DirectionTop) {  // 1011 & 0001
    NSLog(@"top");
}
if (direction & DirectionLeft) {  // 1011 & 0010 
    NSLog(@"left");
}
if (direction & DirectionRight) {  // 1011 & 0100
    NSLog(@"right");
}
if (direction & DirectionBottom) {  // 1011 & 1000
    NSLog(@"bottom");
}
/*
打印的结果
2017-10-30 16:39:35.584816+0800 OBJC_TEST[5215:236112] top
2017-10-30 16:39:35.584825+0800 OBJC_TEST[5215:236112] left
2017-10-30 16:39:35.584831+0800 OBJC_TEST[5215:236112] bottom
*/

enum在Objective-C中的“升级版”

enum State : NSInteger {/*...*/};
// NS_ENUM,定义状态等普通枚举类型
typedef NS_ENUM(NSUInteger, State) {
    StateOK = 0,
    StateError,
    StateUnknow
};
// NS_OPTIONS,定义可组合选项的枚举类型
typedef NS_OPTIONS(NSUInteger, Direction) {
    DirectionNone = 0,
    DirectionTop = 1 << 0,
    DirectionLeft = 1 << 1,
    DirectionRight = 1 << 2,
    DirectionBottom = 1 << 3
};
上一篇 下一篇

猜你喜欢

热点阅读