小码哥iOS学习笔记第十一天: 位运算补充(枚举)

  • 在开发中经常可以看到类似于下面的枚举
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
    UIViewAutoresizingNone                 = 0,
    UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
    UIViewAutoresizingFlexibleWidth        = 1 << 1,
    UIViewAutoresizingFlexibleRightMargin  = 1 << 2,
    UIViewAutoresizingFlexibleTopMargin    = 1 << 3,
    UIViewAutoresizingFlexibleHeight       = 1 << 4,
    UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
复制代码
  • 使用的时候, 多个枚举值之间使用逻辑或(|)连接
UIViewAutoresizing autoresizing = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
复制代码
  • 我们也可以使用这种方式来定义枚举
typedef NS_ENUM(NSInteger, LTSeason) {
    LTSeasonSpring = 1 << 0,    // 0b0001
    LTSeasonSummer = 1 << 1,    // 0b0010
    LTSeasonAutumn = 1 << 2,    // 0b0100
    LTSeasonWinter = 1 << 3     // 0b1000
};
复制代码
  • 使用的时候用逻辑或(|)将他们连起来
LTSeason seasons = LTSeasonSpring | LTSeasonSummer | LTSeasonWinter;
复制代码
  • 这三个枚举值经过逻辑或运算后, seasons的结果如下
 0001
 0010
|1000
------
 1011
 即: seasons = 0b1011
复制代码
  • 通过逻辑或得到的seasons, 我们在使用时, 需要将其拆开, 看看是由哪些枚举值组成的
  • LTSeasonWinter为例, 可以使用下面的方式获取是否含有LTSeasonWinter
 1011
&1000
------
 1000
获取到的结果大于0, 说明含有LTSeasonWinter
复制代码
  • LTSeasonWinter的值正好是1000
  • 所以我们可以通过下面的方式判断, seasons中是否含有指定枚举
- (void)setSeasons:(LTSeason)seasons
{
    if (seasons & LTSeasonSpring) {
        NSLog(@"seasons 包含了 LTSeasonSpring");
    }
    if (seasons & LTSeasonSummer) {
        NSLog(@"seasons 包含了 LTSeasonSummer");
    }
    if (seasons & LTSeasonAutumn) {
        NSLog(@"seasons 包含了 LTSeasonAutumn");
    }
    if (seasons & LTSeasonWinter) {
        NSLog(@"seasons 包含了 LTSeasonWinter");
    }
}
复制代码

转载于:https://juejin.im/post/5c83ac8ae51d453438421d1e

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值