位移枚举
我们在观察一些源代码时,发现有些枚举的结构是1,2,4,8的结构,为什么要采用这样的结构呢,这样的结构方便我们进行多选枚举值.不选默认是0,什么都不做操作,代码如下.
typedef enum {
ZLActionTypeTop = 1 << 0, // 1
ZLActionTypeBottom = 1 << 1, // 2
ZLActionTypeLeft = 1 << 2, // 4
ZLActionTypeRight = 1 << 3, // 8
} ZLActionType;
// | 按位或 只要有一个是1,结果就是1
// & 按位与 只有两个都是1,结果才是1
// ZLActionType type = ZLActionTypeTop | ZLActionTypeBottom | ZLActionTypeRight | ZLActionTypeLeft;
[self test:0];
- (void)test:(ZLActionType)type {
if(type == 0)return;
if ((type & ZLActionTypeTop) == ZLActionTypeTop) {
NSLog(@"上");
}
if ((type & ZLActionTypeBottom) == ZLActionTypeBottom) {
NSLog(@"下");
}
if ((type & ZLActionTypeLeft) == ZLActionTypeLeft) {
NSLog(@"左");
}
if ((type & ZLActionTypeRight) == ZLActionTypeRight) {
NSLog(@"右");
}
}