iOS开发中定义枚举的正确姿式(NS_ENUM VS enum)

iOS开发中枚举也是常常会用到的数据类型之一。最近在整理别人写的老项目的时候,发现枚举的定义使用了多种方式。数组

  • 方式1
typedef enum {
    MJPropertyKeyTypeDictionary = 0, // 字典的key
    MJPropertyKeyTypeArray // 数组的key
} MJPropertyKeyType;
  • 方式2
typedef enum: NSInteger {
        None,
        Melee,
        Fire,
        Ice,
        Posion
    }AttackType;
  • 方式3
typedef NS_ENUM(NSUInteger, MeiziCategory) {
    MeiziCategoryAll = 0,
    MeiziCategoryDaXiong,
    MeiziCategoryQiaoTun,
    MeiziCategoryHeisi,
    MeiziCategoryMeiTui,
    MeiziCategoryQingXin,
    MeiziCategoryZaHui
};
  • 方式4

这种比较特殊支持位操做框架

typedef NS_OPTIONS(NSUInteger, ActionType) {
    ActionTypeUp    = 1 << 0, // 1
    ActionTypeDown  = 1 << 1, // 2
    ActionTypeRight = 1 << 2, // 4
    ActionTypeLeft  = 1 << 3, // 8
};

针对于前三种方式,咱们应该使用那一种更新好呢?
这是来自Stack Overflow的解释。ide

First, NS_ENUM uses a new feature of the C language where you can specify the underlying type for an enum. In this case, the underlying type for the enum is NSInteger (in plain C it would be whatever the compiler decides, char, short, or even a 24 bit integer if the compiler feels like it).

Second, the compiler specifically recognises the NS_ENUM macro, so it knows that you have an enum with values that shouldn't be combined like flags, the debugger knows what's going on, and the enum can be translated to Swift automatically.ui

翻译:this

首先,NS_ENUM使用C语言的一个新特性,您能够在该特性中指定enum的底层类型。在本例中,enum的底层类型是NSInteger(在普通的C语言中,它是编译器决定的任何类型,char、short,甚至是编译器喜欢的24位整数)。

其次,编译器专门识别NS_ENUM宏,所以它知道您有一个enum,它的值不该该像标志那样组合在一块儿,调试器知道发生了什么,而且enum能够自动转换为Swift。翻译

从解释能够看出,定义普通的枚举时,推荐咱们使用第三种方式 NS_ENUM(),定义位移相关的枚举时,咱们则使用 NS_OPTIONS()debug

并且咱们查看苹果的框架,发现苹果使用的也是第三种和第四种。苹果的官方文档也有明确的说明,推荐咱们使用NS_ENUM()NS_OPTIONS()调试

总结:结合Stack Overflow和苹果官方的说明,咱们之后在定义枚举时,应该使用NS_ENUM()NS_OPTIONS(),这样更规范。code

相关文章
相关标签/搜索