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
There are a lot of great answers to this here: Converting between C enum and XML
They are basically the same as Abizern's, but are a little cleaner and easier to work with if your app does this string-to-enum conversion a lot. There are solutions which keep the string and enum definitions together, and ways to make the conversions each a single, easy-to-read line of code.
// ...
typedef enum {
One = 0,
Two,
Three
} GFN;
// ...
#define kGFNPrefix @"GFNEnum_"
// ...
+ (NSString *)gfnToStr:(GFN)gfn {
return [NSString stringWithFormat:@"%@%d", kGFNPrefix, gfn];
}
+ (GFN)gfnFromStr:(NSString *)str {
NSString *gfnStr = [str stringByReplacingOccurrencesOfString:kGFNPrefix withString:@""];
return [gfnStr intValue];
}
// ...
My choice =)
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));
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];
I found the solution:
if ([car_color isEqualToString:@"1"])
return red;
if ([tipo_pdi isEqualToString:@"2"])
return blue;
if ([tipo_pdi isEqualToString:@"3"])
return white;
But I don't like this 'if' style, what if I had a thousand colors? Isn't there a more automatic solution?
You could also put the values in an array.
NSArray *carColorsArray = @[@"red", @"blue", @"white"];
You can then use indexOfObject to get the index of a particular string.
car_colors carColor = [carColorsArray indexOfObject:@"blue"] + 1;