Objective-c: NSString to enum

后端 未结 6 1635
滥情空心
滥情空心 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:40

    here's an implementation using NSDictionary and the existing enum

    in .h file:

    typedef NS_ENUM(NSInteger, City) {
        Toronto         = 0,
        Vancouver       = 1
     };
    
    @interface NSString (EnumParser)
    - (City)cityEnumFromString;
    @end
    

    in .m file:

    @implementation NSString (EnumParser)
    
    - (City)cityEnumFromString{
        NSDictionary *cities = @{
                                @"Toronto": @(Toronto),
                                @"Vancouver": @(Vancouver),
                                };
        return cities[self].integerValue;
    }
    
    @end
    

    sample usage:

    NSString *myCity = @"Vancouver";
    City enumValue = [myCity cityEnumFromString];
    
    NSLog(@"Expect 1, Actual %@", @(enumValue));
    

提交回复
热议问题