Can Objective-C switch on NSString?

James Raitsev picture James Raitsev · Nov 17, 2011 · Viewed 98.4k times · Source

Is there a more intelligent way to rewrite this?

if ([cardName isEqualToString:@"Six"]) {
    [self setValue:6];
} else if ([cardName isEqualToString:@"Seven"]) {
    [self setValue:7];
} else if ([cardName isEqualToString:@"Eight"]) {
    [self setValue:8];
} else if ([cardName isEqualToString:@"Nine"]) {
    [self setValue:9];
} 

Answer

Chris picture Chris · Nov 17, 2011

Unfortunately they cannot. This is one of the best and most sought after utilizations of switch statements, so hopefully they hop on the (now) Java (and others) bandwagon!

If you are doing card names, perhaps assign each card object an integer value and switch on that. Or perhaps an enum, which is considered as a number and can therefore be switched upon.

e.g.

typedef enum{
  Ace, Two, Three, Four, Five ... Jack, Queen, King

} CardType;

Done this way, Ace would be be equal to case 0, Two as case 1, etc.