想要了解位移枚举,得先熟悉位运算符。主要是两个,’ | ‘和 ‘ & ‘。和逻辑运算符’ || ‘ ‘ && ‘不同,位运算符是对二进制数字按位进行与或操作。比如2&3,就是把2和3先转换为2进制数10和11,再按位作与运算,得到结果10,即2。同理,2|3结果为11,即3。下面具体举个例子。
先自定义一个位移枚举:
typedef NS_OPTIONS(NSUInteger, ActionType){
ActionTypeUp = 1 << 0,
ActionTypeDown = 1 << 1,
ActionTypeLeft = 1 << 2,
ActionTypeRight = 1 << 3,
};
再写一个方法:
- (void)action:(ActionType)type
{
if (type == 0)
{
return;
}
if ((type & ActionTypeUp) == ActionTypeUp)
{
NSLog(@"上");
}
if ((type & ActionTypeDown) == ActionTypeDown)
{
NSLog(@"下");
}
if ((type & ActionTypeLeft) == ActionTypeLeft)
{
NSLog(@"左");
}
if ((type & ActionTypeRight) == ActionTypeRight)
{
NSLog(@"右");
}
},最后在touchesBegan里面调用一下:
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
ActionType type = ActionTypeUp | ActionTypeDown | ActionTypeLeft | ActionTypeRight;
[self action:type];
},
最后上下左右全都有输出。
ActionTypeUp | ActionTypeDown | ActionTypeLeft | ActionTypeRight做完按位或运算后得到结果为1111,在action方法中1111与任意一个枚举做与运算结果都不会改变枚举值,所以所有的都可以输出了。
关于 ActionTypeUp = 1 << 0这种格式的疑问,开始也没大看懂,把每种枚举类型打印一下:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"%zd",ActionTypeUp);
NSLog(@"%zd",ActionTypeDown);
NSLog(@"%zd",ActionTypeLeft);
NSLog(@"%zd",ActionTypeRight);
}
打印结果为:
1
2
4
8
我们把”<<“左边的数字改为2:
typedef NS_OPTIONS(NSUInteger, ActionType){
ActionTypeUp = 2 << 0,
ActionTypeDown = 2 << 1,
ActionTypeLeft = 2 << 2,
ActionTypeRight = 2 << 3,
};
再打印一下,得到结果:
2
4
8
16
是不是明白了?还不明白?那好,把2改为二进制形式”10", ActionTypeUp = 2 << 0,我们把”<<“右边的数字理解为”往左位移0位”,结果还是10,所以ActionTypeDown = 2 << 1这个东西就应该是100,也就是4,以此类推。。。明白了吗?”<<“左边是位移的起点数,右边是位移偏移量,就这么简单。
你是不是还想到了一种新的形势?
typedef NS_OPTIONS(NSUInteger, ActionType){
ActionTypeUp = 8 >> 0,
ActionTypeDown = 8 >> 1,
ActionTypeLeft = 8 >> 2,
ActionTypeRight = 8 >> 3,
};
自己动手看看吧。