Can Objective-C switch on NSString?

后端 未结 14 1146
不知归路
不知归路 2020-12-04 05:40

Is there a more intelligent way to rewrite this?

if ([cardName isEqualToString:@\"Six\"]) {
    [self setValue:6];
} else if ([cardName isEqualToString:@\"Se         


        
14条回答
  •  难免孤独
    2020-12-04 06:32

    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]];
    

提交回复
热议问题