Can Objective-C switch on NSString?

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

    You could set up a dictionary of blocks, like this:

    NSString *lookup = @"Hearts"; // The value you want to switch on
    
    typedef void (^CaseBlock)();
    
    // Squint and this looks like a proper switch!
    NSDictionary *d = @{
        @"Diamonds": 
        ^{ 
            NSLog(@"Riches!"); 
        },
        @"Hearts":
        ^{ 
            self.hearts++;
            NSLog(@"Hearts!"); 
        },
        @"Clubs":
        ^{ 
            NSLog(@"Late night coding > late night dancing"); 
        },
        @"Spades":
        ^{ 
            NSLog(@"I'm digging it"); 
        }
    };
    
    ((CaseBlock)d[lookup])(); // invoke the correct block of code
    

    To have a 'default' section, replace the last line with:

    CaseBlock c = d[lookup];
    if (c) c(); else { NSLog(@"Joker"); }
    

    Hopefully Apple will teach 'switch' a few new tricks.

提交回复
热议问题