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
}
具体用哪种枚举还是要看具体情况。