How to use `typedef NS_ENUM` to return `float` values?

前端 未结 2 672
迷失自我
迷失自我 2021-01-23 19:02

In the code (below) LINE_WIDTH is declared a typedef for enumeration where the names Large, Medium, Small and Hairline are int co

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-23 19:39

    Objective-C doesn't support non-integer enum values. Your only option is to provide code that converts the enum value to a float value.

    One option is to create a simple function such as:

    float LINE_WIDTH_float(LINE_WIDTH width);
    

    Put that in the same .h as the enum declaration. Then add the following to some appropriate .m or .c file:

    float LINE_WIDTH_float(LINE_WIDTH width) {
        switch (width) {
            case LINE_WIDTH_Large:
                return 1.5f;
            case LINE_WIDTH_Medium:
                return 1.0f;
            case LINE_WIDTH_Small:
                return 0.5f;
            case LINE_WIDTH_Hairline:
                return 0.25f;
            default:
                return 0.0f;
        }
    }
    

    So somewhere you have an enum value:

    LINE_WIDTH someWidth = LINE_WIDTH_Medium;
    float width = LINE_WIDTH_float(someWidth);
    

    Another option would be to define an array of float.

    In the same .h as the enum add:

    extern float *LINE_WIDTH_float;
    

    Then in some appropriate .m or .c, you can add:

    float *LINE_WIDTH_float = { 1.5, 1.0, 0.5, 0.25 };
    

    Then to use this you can do:

    LINE_WIDTH someWidth = LINE_WIDTH_Medium;
    float width = LINE_WIDTH_float[someWidth];
    

    Note that this is less safe than the first approach. It will likely crash if your enum value is set to something other than a valid enum value or if you add a new enum value but forget to update the values in the array.

提交回复
热议问题