位移枚舉
一. OC中常見的三種枚舉
-
C語言枚舉
// C語言枚舉 typedef enum : NSUInteger { FHDemoTypeA, FHDemoTypeB, FHDemoTypeC, } FHDemoType;
-
OC枚舉:
強烈建議大家在日常編程中使用OC枚舉
// OC枚舉 typedef NS_ENUM(NSUInteger, FHNSType) { FHNSTypeA, FHNSTypeB, FHNSTypeC, };
-
位移枚舉:
用于多值判斷
位移枚舉中使用
1 << x
來設置枚舉值1 << x
代表將二進制0001
中的1, 向左移動x位通過
按位或: |
, 拼接兩個枚舉值-
通過
按位與: &
, 可以從一個枚舉值中取出不同的值// 位移枚舉 typedef NS_OPTIONS(NSUInteger, FHActionType) { FHActionTypeTop = 1 << 0, FHActionTypeBottom = 1 << 1, FHActionTypeLeft = 1 << 2, FHActionTypeRight = 1 << 3, }; 0001 0010 | 拼接兩個值 ------ 0011 0011 0010 & 通過一個值, 可以取出兩個不同的值 ------ 0010 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { // 一般枚舉值為0的,代表性能最好的枚舉值 [self demo: FHActionTypeRight | FHActionTypeTop]; } - (void)demo:(int)type { if (type & FHActionTypeTop) { NSLog(@"向上--%ld", type & FHActionTypeTop); } if (type & FHActionTypeBottom) { NSLog(@"向下--%ld", type & FHActionTypeBottom); } if (type & FHActionTypeLeft) { NSLog(@"向左--%ld", type & FHActionTypeLeft); } if (type & FHActionTypeRight) { NSLog(@"向右--%ld", type & FHActionTypeRight); } }