Can Objective-C switch on NSString?

后端 未结 14 1107
不知归路
不知归路 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条回答
  •  -上瘾入骨i
    2020-12-04 06:09

    There are other ways to do that, but switch isn't one of them.

    If you only have a few strings, as in your example, the code you have is fine. If you have many cases, you could store the strings as keys in a dictionary and look up the corresponding value:

    NSDictionary *cases = @{@"Six" : @6,
                            @"Seven" : @7,
                            //...
                           };
    
    NSNumber *value = [cases objectForKey:cardName];
    if (value != nil) {
        [self setValue:[value intValue]];
    }
    

提交回复
热议问题