- 开发中,我们经常看到很多的位移枚举,一般来说,见到位移枚举,我们都是可以写多个的,用 | 来隔开,就能识别。其实按照习惯的惯例,我们通常看到枚举,看不懂,就写个0,其实这样不好,还是要理解一下枚举的内容,是不是我们想要的
- 那么我们来模拟一下,看位移枚举,究竟是个什么东西
自定义一个枚举
根据位移的常识,我们得出了偏移后的数值
typedef NS_OPTIONS(NSUInteger, ActionType) {
ActionTypeUp = 1 << 0, // 1
ActionTypeDown = 1 << 1, // 2
ActionTypeRight = 1 << 2, // 4
ActionTypeLeft = 1 << 3, // 8
};
- 我们在一个方法里边:
- (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(@"右");
}
}
- 那么我们在viewDidLoad中 这么搞:
- (void)viewDidLoad {
[super viewDidLoad];
ActionType type = ActionTypeUp | ActionTypeLeft | ActionTypeRight | ActionTypeDown; // 15
[self action:type];
}
其实这个东西,只要懂点二进制的位移的偏移,就知道是什么内容了