【object C】ObjectC中如何彌補switch引數不能為字串的方法

pengfoo發表於2013-06-06

參考:

http://stackoverflow.com/questions/8161737/can-objective-c-switch-on-nsstring

NSString *lookup = @"Hearts"; // The value you want to switch on

typedef void (^CaseBlock)();

// Squint and this looks like a proper switch block!
// New ObjC syntax makes the NSDictionary creation cleaner.
NSDictionary *d = @{
    @"Diamonds": 
    ^() { 
        NSLog(@"Riches!"); 
    },
    @"Clubs":
    ^() { 
        NSLog(@"Clubs"); 
    },
    @"Spades":
    ^() { 
        NSLog(@"Spades"); 
    },
    @"Hearts":
    ^() { 
        self.hearts++;
        NSLog(@"Hearts!"); 
    }
};

((CaseBlock)d[lookup])(); // invoke the correct block of code

 Unfortunately this simple alternative doesn't support 'default', nor fall-through, and it'll crash if the lookup value isn't found. To avoid the crash, and have some default code, the last line could be:
CaseBlock c = d[lookup];
if (c) c(); else { NSLog(@"Joker"); }


 

相關文章