目标C - 什么时候"typedef"应该在"enum"之前,什么时候应该枚举enum?

Sco*_*ton 15 enums typedef objective-c

在示例代码中,我看到了这样的:

typedef enum Ename { Bob, Mary, John} EmployeeName;
Run Code Online (Sandbox Code Playgroud)

还有这个:

typedef enum {Bob, Mary, John} EmployeeName;
Run Code Online (Sandbox Code Playgroud)

还有这个:

typedef enum {Bob, Mary, John};
Run Code Online (Sandbox Code Playgroud)

但为我成功编译的是:

enum {Bob, Mary, John};
Run Code Online (Sandbox Code Playgroud)

我将该行放在@interface行上方的.h文件中,然后当我将该.h文件#import转换为另一个类的.m文件时,方法可以看到枚举.

那么,何时需要其他变种?

如果我可以将枚举命名为EmployeeNames,然后,当我键入"EmployeeNames"后跟一个"."时,如果弹出一个列表显示枚举选项是什么,那就太好了.

Dan*_*ker 22

在C(以及目标C)中,枚举类型必须在enum每次使用时都以前缀为前缀.

enum MyEnum enumVar;
Run Code Online (Sandbox Code Playgroud)

通过制作typedef:

typedef MyEnum MyEnumT;
Run Code Online (Sandbox Code Playgroud)

你可以写更短的:

MyEnumT enumVar;
Run Code Online (Sandbox Code Playgroud)

替代声明在一个声明中声明枚举本身和typedef.

// gives the enum itself a name, as well as the typedef
typedef enum Ename { Bob, Mary, John} EmployeeName;

// leaves the enum anonymous, only gives a name to the typedef
typedef enum {Bob, Mary, John} EmployeeName;

// leaves both anonymous, so Bob, Mary and John are just names for values of an anonymous type
typedef enum {Bob, Mary, John};
Run Code Online (Sandbox Code Playgroud)