Best way to enum NSString

前端 未结 7 708
广开言路
广开言路 2021-02-02 13:23

Im digging for ways to enum objc object such as NSString, I remember there a new feature in a version of Xcode4+ which offering a new way to enum , but not clearly. Anyone know

7条回答
  •  广开言路
    2021-02-02 13:28

    Recommended way from apple docs:

    You use the NS_TYPED_ENUM to group constants with a raw value type that you specify. Use NS_TYPED_ENUM for sets of constants that can't logically have values added in a Swift extension, and use NS_TYPED_EXTENSIBLE_ENUM for sets of constants that can be expanded in an extension. Apple docs

    typedef NSString *MyEnum NS_TYPED_ENUM;
    extern MyEnum const MyEnumFirstValue;
    extern MyEnum const MyEnumSecondValue;
    extern MyEnum const MyEnumThirdValue;
    

    in the .h file. Define your strings in the .m file

    MyEnum const MyEnumFirstValue = @"MyEnumFirstValue"
    MyEnum const MyEnumSecondValue = @"MyEnumSecondValue";
    MyEnum const MyEnumThirdValue = @"MyEnumThirdValue";
    

    Works as expected in both Objective-C

    - (void)methodWithMyEnum:(MyEnum)myEnum { }
    

    and Swift

    func method(_ myEnum: MyEnum) { }
    

提交回复
热议问题