OC中枚举关联值

作者: 番茄炒西红柿啊 | 来源:发表于2018-07-11 15:33 被阅读147次

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

    相关文章

      网友评论

        本文标题:OC中枚举关联值

        本文链接:https://www.haomeiwen.com/subject/ztmhpftx.html