iOS - 开发技巧iOS 进阶Wi-Fi参考

iOS - 枚举(Enum)

2018-01-03  本文已影响68人  SkyMing一C
图片源于网络

枚举(Enum)

enum与状态(states)

定义一个枚举类型
//定义枚举类型    
typedef enum _SKYState {
    SKYStateOK  = 0,
    SKYStateError,
    SKYStateUnknow
} SKYState;

//指明枚举类型
//-------in parameters---------------    
@property (nonatomic,assign) SKYState state; //操作类型  

typedef为C语言的关键字,作用是为一种数据类型定义一个新名字。这里的数据类型包括内部数据类型(int,char等)和自定义的数据类型(struct等)。

使用一个枚举类型
- (void)dealWithState:(SKYState)state {
    switch (state) {
        case SKYStateOK:
            //...
            break;
        case SKYStateError:
            //...
            break;
        case SKYStateUnknow:
            //...
            break;
    }
}

enum与选项 (options)

选项 (options) : 就是说一个“选项变量”的类型要能够同时表示一个或多个组合的选择

定义一个枚举类型
//方向,可同时支持一个或多个方向
typedef enum _SKYDirection {
    SKYDirectionNone = 0,// 0  0
    SKYDirectionTop = 1 << 0,// 1  1
    SKYDirectionLeft = 1 << 1,// 2  10 转换成 10进制  2 
    SKYDirectionRight = 1 << 2,// 4  100 转换成 10进制  4 
    SKYDirectionBottom = 1 << 3// 8  1000 转换成 10进制  8 
} SKYDirection;
    SKYDirectionNone    0 0 0 0 0 0 0 0
    SKYDirectionTop     0 0 0 0 0 0 0 1
    SKYDirectionLeft    0 0 0 0 0 0 1 0
    SKYDirectionRight   0 0 0 0 0 1 0 0
    SKYDirectionBottom  0 0 0 0 0 0 0 0
使用一个枚举类型
//用“或”运算同时赋值多个选项
SKYDirection direction = SKYDirectionTop | SKYDirectionLeft | SKYDirectionBottom;

//用“与”运算取出对应位
if (direction && SKYDirectionTop) {
    NSLog(@"top");
}
if (direction && SKYDirectionLeft) {
    NSLog(@"left");
}
if (direction && SKYDirectionRight) {
    NSLog(@"right");
}
if (direction && SKYDirectionBottom) {
    NSLog(@"bottom");
}

enum与Objective-C

#define NS_ENUM(...) CF_ENUM(__VA_ARGS__)
#define NS_OPTIONS(_type, _name) CF_OPTIONS(_type, _name)
//NS_ENUM,定义状态等普通枚举
typedef NS_ENUM(NSUInteger, SKYState) {
    SKYStateOK  = 0,
    SKYStateError,
    SKYStateUnknow
};

//方向,可同时支持一个或多个方向
//NS_OPTIONS,定义选项
typedef NS_OPTIONS(NSUInteger, SKYDirection) {
    SKYDirectionNone = 0,// 0  0
    SKYDirectionTop = 1 << 0,// 1  1
    SKYDirectionLeft = 1 << 1,// 2  10 转换成 10进制  2 
    SKYDirectionRight = 1 << 2,// 4  100 转换成 10进制  4 
    SKYDirectionBottom = 1 << 3// 8  1000 转换成 10进制  8 
};

参考

IOS开发之----enum与typedef enum的用法

ios高效开发-正确的使用枚举(Enum)

上一篇 下一篇

猜你喜欢

热点阅读