enum Values to NSString (iOS)

前端 未结 16 1892
悲&欢浪女
悲&欢浪女 2020-12-04 07:57

I have an enum holding several values:

enum {value1, value2, value3} myValue;

In a certain point in my app, I wish to check which value of

16条回答
  •  情深已故
    2020-12-04 08:20

    I didn't like putting the enum on the heap, without providing a heap function for translation. Here's what I came up with:

    typedef enum {value1, value2, value3} myValue;
    #define myValueString(enum) [@[@"value1",@"value2",@"value3"] objectAtIndex:enum]
    

    This keeps the enum and string declarations close together for easy updating when needed.

    Now, anywhere in the code, you can use the enum/macro like this:

    myValue aVal = value2;
    NSLog(@"The enum value is '%@'.", myValueString(aVal));
    
    outputs: The enum value is 'value2'.
    

    To guarantee the element indexes, you can always explicitly declare the start(or all) enum values.

    enum {value1=0, value2=1, value3=2};
    

提交回复
热议问题