美文网首页
高效编写代码的方法(三):枚举

高效编写代码的方法(三):枚举

作者: 蜂猴 | 来源:发表于2016-04-23 12:09 被阅读112次

其实枚举在日常开发中我们已经使用很多了,也就不多做一些教学类的介绍。
分享一下我在书中学习到的关于枚举的新知识。

typedef

比如网络加载状态枚举,没有typedef的情况下,我们这样写枚举:

enum FHNetWorkLoadState{
    FHNetWorkLoadStateNone = 0,
    FHNetWorkLoadStateLoading,
    FHNetWorkLoadStateFinish
};

这样在后续使用中就会带来比较多的麻烦,要声明一个枚举类型的值,我们只能这么写:

enum FHNetWorkLoadState loadState = FHNetWorkLoadStateFinish;

显得多余很不方便。
此时使用typedef enum的好处就凸显出来。

我的理解是,typedef关键字可以将枚举声明称一个“类”,当然不是真的类。然后我们就可以更广泛的去使用枚举值,包括函数的参数,返回值,switch语句等。

NS_OPTIONS

我们经常可以在iOS框架中看到一些特殊的枚举类采用位操作来表示。如下:

typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
    UIViewAutoresizingNone                 = 0,
    UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
    UIViewAutoresizingFlexibleWidth        = 1 << 1,
    UIViewAutoresizingFlexibleRightMargin  = 1 << 2,
    UIViewAutoresizingFlexibleTopMargin    = 1 << 3,
    UIViewAutoresizingFlexibleHeight       = 1 << 4,
    UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};

位操作的介绍就不多说了。还是关注一下NS_OPTIONS 关键字

与NS_OPTIONS 相对的还有NS_ENUM,两者的差别在于枚举的类型,也就是该枚举类型能否支持位操作。
在UIKit的框架中,可以找到一个系统定义的宏:

#if (__cplusplus && __cplusplus >= 201103L && (__has_extension(cxx_strong_enums) || __has_feature(objc_fixed_enum))) || (!__cplusplus && __has_feature(objc_fixed_enum))  
#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type  
#if (__cplusplus)  
#define NS_OPTIONS(_type, _name) _type _name; enum : _type  
#else  
#define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type  
#endif  
#else  
#define NS_ENUM(_type, _name) _type _name; enum  
#define NS_OPTIONS(_type, _name) _type _name; enum  
#endif  

之所以苹果要写这样大量包含IF的宏,原因主要是以下:
检查编译器是否完全支持新类型的宏。如果编译器不支持位操作的NS_OPTION,那么自动转为NS_ENUM。

总结

  • 1 使用枚举的时候名称的可读性要强。
  • 2 多使用NS_OPTIONS 和NS_ENUM关键字。

相关文章

网友评论

      本文标题:高效编写代码的方法(三):枚举

      本文链接:https://www.haomeiwen.com/subject/cjwxrttx.html