相較于oc中的枚舉,swift中的枚舉有個(gè)rawValue,即關(guān)聯(lián)值的存在.這樣方便了枚舉的定義,也使枚舉的定義不在局限于整型.
- 比如定義一個(gè)string類型的枚舉,以及獲取關(guān)聯(lián)值,如下:
enum SwiftEnum: String {
case red = "redType"
case white = "whiteType"
case black = "blackType"
}
let type = SwiftEnum.black
_ = type.rawValue // "blackType"
- oc中枚舉定義如下:
typedef NS_ENUM(NSInteger, TestType) {
TestTypeDefault = 1,
TestTypeWhite,
TestTypeBlack
};
能否像swift那樣給每個(gè)枚舉也關(guān)聯(lián)一個(gè)關(guān)聯(lián)值呢.答案當(dāng)然是可以的.語法格式如下:
// 關(guān)聯(lián)一個(gè)NSString類型的關(guān)聯(lián)值
NSString *const TestTypeDescription[] = {
[TestTypeDefault] = @"default",
[TestTypeWhite] = @"white",
[TestTypeBlack] = @"black"
};
TestType type = TestTypeBlack;
NSString *description = TestTypeDescription[type];
NSLog(@"%ld, %@", (long)type, description);
// 3, black
tips: 個(gè)人覺得這個(gè)功能還是挺好的,某些時(shí)候能夠用到,挺方便的.