iOS中关于NS_ENUM和NS_OPTIONS之间的差别

iOS枚举代码:

1、NS_ENUM:放的是整形,代码:

typedef NS_ENUM(NSInteger, MyCountry) {
    MyCountryDefault,
    MyCountryCustom
};

2:NS_OPTIONS:放的是位掩码,代码:

typedef NS_OPTIONS(NSInteger, MyCountry){
    MyCountry1 = 1 << 0,
    MyCountry2 = 1 << 1,
};

区别主要还是看适合用在什么地方:

枚举数据代表的是2个国家,第一个值zhi是缺省国家,第二值个是自定义国家:

如果只是简单判断一下国家的话可以这样用:

switch (style){
    case MyCountryDefault:
        // int is 0
    break;
    case MyCountryCustom:
        // int is 1
    break;
}

但是,如果想要判断多个国家的话,这样用就有点勉强了,但是可以使用位掩码是完成该功能:

typedef NS_OPTIONS(NSInteger, MyCountry) {
    MyCountry1 = 1 << 0, // bits: 0001
    MyCountry2 = 1 << 1, // bits: 0010
};

if (option & MyCountry1){ // last bit is 1
    // bits are 0001 or 0011
}
if (option & MyCountry2){ // second to last bit is 1
    // bits are 0010 or 0011
}
if (option & MyCountry1 & MyCountry2){ // last two bits are 1
    // bits are 0011
}

具体用哪种枚举还是要看具体情况。

转载于:https://my.oschina.net/caijunrong/blog/488427

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值