其實枚舉在日常開發(fā)中我們已經(jīng)使用很多了逃默,也就不多做一些教學(xué)類的介紹。
分享一下我在書中學(xué)習(xí)到的關(guān)于枚舉的新知識簇搅。
typedef
比如網(wǎng)絡(luò)加載狀態(tài)枚舉,沒有typedef的情況下软吐,我們這樣寫枚舉:
enum FHNetWorkLoadState{
FHNetWorkLoadStateNone = 0,
FHNetWorkLoadStateLoading,
FHNetWorkLoadStateFinish
};
這樣在后續(xù)使用中就會帶來比較多的麻煩瘩将,要聲明一個枚舉類型的值,我們只能這么寫:
enum FHNetWorkLoadState loadState = FHNetWorkLoadStateFinish;
顯得多余很不方便凹耙。
此時使用typedef enum的好處就凸顯出來姿现。
我的理解是,typedef關(guān)鍵字可以將枚舉聲明稱一個“類”肖抱,當然不是真的類备典。然后我們就可以更廣泛的去使用枚舉值,包括函數(shù)的參數(shù)意述,返回值提佣,switch語句等。
NS_OPTIONS
我們經(jīng)郴绯纾可以在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
};
位操作的介紹就不多說了。還是關(guān)注一下NS_OPTIONS 關(guān)鍵字
與NS_OPTIONS 相對的還有NS_ENUM术荤,兩者的差別在于枚舉的類型倚喂,也就是該枚舉類型能否支持位操作。
在UIKit的框架中瓣戚,可以找到一個系統(tǒng)定義的宏:
#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,那么自動轉(zhuǎn)為NS_ENUM舱权。
總結(jié)
- 1 使用枚舉的時候名稱的可讀性要強矗晃。
- 2 多使用NS_OPTIONS 和NS_ENUM關(guān)鍵字。