OC中枚举关联值

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

  • 比如定义一个string类型的枚举,以及获取关联值,如下:
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那样给每个枚举也关联一个关联值呢.答案当然是可以的.语法格式如下:

// 关联一个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: 个人觉得这个功能还是挺好的,某些时候能够用到,挺方便的.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容