Objective-c: NSString to enum
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];
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;