macOS开发备忘录

OC中枚举关联值

2018-07-11  本文已影响147人  番茄炒西红柿啊

相较于oc中的枚举,swift中的枚举有个rawValue,即关联值的存在.这样方便了枚举的定义,也使枚举的定义不在局限于整型.

enum SwiftEnum: String {
    case red = "redType"
    case white = "whiteType"
    case black = "blackType"
}

let type = SwiftEnum.black
 _ = type.rawValue // "blackType"
typedef NS_ENUM(NSInteger, TestType) {
    TestTypeDefault = 1,
    TestTypeWhite,
    TestTypeBlack
};

能否像swift那样给每个枚举也关联一个关联值呢.答案当然是可以的.语法格式如下:

// 关联一个NSString类型的关联值
NSString *const TestTypeDescription[] = {
    [TestTypeDefault] = @"default",
    [TestTypeWhite] = @"white",
    [TestTypeBlack] = @"black"
};

 TestType type = TestTypeBlack;
 NSString *description = TestTypeDescription[type];
 NSLog(@"%ld, %@", (long)type, description);
// 3, black

tips: 个人觉得这个功能还是挺好的,某些时候能够用到,挺方便的.

上一篇 下一篇

猜你喜欢

热点阅读