Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-c: NSString to enum

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_colors: car_colors myCar;

The question is, I receive the color of the car in a NSString. It must be a NSString, I can't change that. How can I convert from NSString to car_colors type?

NSString *value = [[NSString alloc] initWithString:@"1"];
myCar = [value intValue]; // <-- doesn't work

any idea? thanks!

like image 412
Hectoret Avatar asked Sep 09 '25 16:09

Hectoret


1 Answers

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<NSString*,NSNumber*> *cities = @{
                            @"Toronto": @(Toronto),
                            @"Vancouver": @(Vancouver),
                            };
    return cities[self].integerValue;
}

@end

sample usage:

NSString *myCity = @"Vancouver";
City enumValue = [myCity cityEnumFromString];

NSLog(@"Expect 1, Actual %@", @(enumValue));