[Objective-C] 枚舉ENUM

#Objective-C 枚舉ENUMcode

##簡單枚舉 ###定義it

typedef NS_ENUM(NSUInteger, Type) {
    //用戶未持有券的狀態
    TypeA = 0,
    TypeB = 1,
    TypeC = 2,
}

###使用io

Type type = TypeA;

//if 語句
if (status9==CouponStatus_UserGet) {
	//your code
}

//switch 語句
switch (type) {
        case TypeA:
            //your code
            break;
        case TypeB:
            //your code
            break; 
        default:
            break;
}

##高級枚舉原理

###定義request

typedef NS_ENUM(NSUInteger, Type) {
    TypeA = 1 << 0,
    TypeB = 1 << 1,
    TypeC = 1 << 2,
    
    TypeD = TypeA|TypeB,
}
使用<<屬於枚舉的高級用法
a<<N: 右移符號,按二級制向右右移N位,多出來的位置,由0補充
3 << 2 = 0b11<<3 即0b1100

###使用error

下面一種常見的用法推送

[[UNUserNotificationCenter currentNotificationCenter] 
requestAuthorizationWithOptions:(UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
                    NSLog(@"iOS10註冊消息推送:%@",granted?@"成功":@"失敗");
                }];

參數中出現了這樣一個參數(UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert)消息推送

很顯然是想同時實現3種狀況。那麼它的內部實現是怎麼的?ant

- (void)options:(Type)type
{
	if(type&TypeA){
		//your code
	}
	if(type&TypeB){
		//your code
	}
	if(type&TypeC){
		//your code
	}
}

//原理解析
TypeA = 1 << 0 , 0b1<<0 = 0b1 = 1
TypeB = 1 << 1 , 0b1<<1 = 0b10 = 2
TypeC = 1 << 2 , 0b1<<2 = 0b100 = 4
TypeD = TypeA|TypeB = 1|2 = 0b1| 0b10= 0b11 = 3
//下面計算
TypeD&TypeA = 3 & 1 = 0b11 & 0b1 = 0b01 = 1
TypeD&TypeC = 3 & 4 = 0b11 & 0b100 = 0b000 = 0
相關文章
相關標籤/搜索