typedef NS_ENUM与typedef枚举 [英] typedef NS_ENUM vs typedef enum

查看:196
本文介绍了typedef NS_ENUM与typedef枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用现代Objective-C 指南,Apple建议使用NS_ENUM宏而不是枚举。我还阅读了 NSHipster 中关于NS_ENUM和NS_OPTIONS的解释。

On the Adopting Modern Objective-C guide, Apple recommends using the NS_ENUM macro instead of enum. I've also read an explanation from NSHipster about NS_ENUM and NS_OPTIONS.

也许我已经错过了一些东西,但是我不太明白以下两个代码片段之间的区别,如果有的话, NS_ENUM 是推荐的处理方式(除非

Maybe I've missed something but I don't quite understand what is the difference between the following two snippets and if any why is NS_ENUM the recommended way to go (except maybe, for backwards compatibility with older compilers)

// typedef enum
typedef enum {
    SizeWidth,
    SizeHeight
}Size;

// typedef NS_ENUM
typedef NS_ENUM(NSInteger, Size) {
    SizeWidth,
    SizeHeight
};


推荐答案

首先,NS_ENUM使用C语言的新功能您可以在其中指定枚举的基础类型。在这种情况下,枚举的基础类型是NSInteger(在普通C语言中,这是编译器决定的结果,char,short或什至是24位整数(如果编译器感觉像的话))。

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).

第二,编译器专门识别NS_ENUM宏,因此它知道您有一个枚举,其值不应像标志那样组合,调试器知道发生了什么,该枚举可以自动转换为Swift。

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.

这篇关于typedef NS_ENUM与typedef枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆