Can Objective-C switch on NSString?

后端 未结 14 1140
不知归路
不知归路 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:31

    Building on @Graham Perks idea posted earlier, designed a simple class to make switching on strings fairly simple and clean.

    @interface Switcher : NSObject
    
    + (void)switchOnString:(NSString *)tString
                     using:(NSDictionary *)tCases
               withDefault:(CaseBlock)tDefaultBlock;
    
    @end
    
    @implementation Switcher
    
    + (void)switchOnString:(NSString *)tString
                     using:(NSDictionary *)tCases
               withDefault:(CaseBlock)tDefaultBlock
    {
        CaseBlock blockToExecute = tCases[tString];
        if (blockToExecute) {
            blockToExecute();
        } else {
            tDefaultBlock();
        }
    }
    
    @end
    

    You would use it like this:

    [Switcher switchOnString:someString
                       using:@{
                                   @"Spades":
                                   ^{
                                       NSLog(@"Spades block");
                                   },
                                   @"Hearts":
                                   ^{
                                       NSLog(@"Hearts block");
                                   },
                                   @"Clubs":
                                   ^{
                                       NSLog(@"Clubs block");
                                   },
                                   @"Diamonds":
                                   ^{
                                       NSLog(@"Diamonds block");
                                   }
                               } withDefault:
                                   ^{
                                       NSLog(@"Default block");
                                   }
     ];
    

    The correct block will execute according to the string.

    Gist for this solution

提交回复
热议问题