Is there a more intelligent way to rewrite this?
if ([cardName isEqualToString:@\"Six\"]) {
[self setValue:6];
} else if ([cardName isEqualToString:@\"Se
Unfortunately, switch statements can only be used on primitive types. You do have a few options using collections, though.
Probably the best option would be to store each value as an entry in an NSDictionary.
NSDictionary *stringToNumber = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:6],@"Six",
[NSNumber numberWithInt:7],@"Seven",
[NSNumber numberWithInt:8],@"Eight",
[NSNumber numberWithInt:9],@"Nine",
nil];
NSNumber *number = [stringToNumber objectForKey:cardName];
if(number) [self setValue:[number intValue]];
Here is the more intelligent way to write that. It's to use an NSNumberFormatter
in the "spell-out style":
NSString *cardName = ...;
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterSpellOutStyle];
NSNumber *n = [nf numberFromString:[cardName lowercaseString]];
[self setValue:[n intValue]];
[nf release];
Note that the number formatter wants the string to be lowercased, so we have to do that ourselves before passing it in to the formatter.