Objective-c: NSString to enum

后端 未结 6 1647
滥情空心
滥情空心 2021-01-31 04:24

So, I\'ve got this definition:

typedef enum {
    red = 1,
    blue = 2,
    white = 3
} car_colors;

Then, I\'ve got a variable of type car_col

6条回答
  •  时光取名叫无心
    2021-01-31 04:45

    Rather than use an array, why not use a dictionary; You have the colour NSString as keys, and you return whatever NSNumber you want. Something like; (Long winded for clarity).

    NSDictionary *carColourDictionary = @{@"Red": @1,
                                          @"Blue": @2,
                                          @"White": @3};
    
    // Use the dictionary to get the number
    // Assume you have a method that returns the car colour as a string:
    // - (NSString *)colourAsString;
    int carColour = carColourDictionary[object colourAsString];
    

提交回复
热议问题