Created
April 4, 2013 23:59
-
-
Save wjlafrance/5315490 to your computer and use it in GitHub Desktop.
Switching on objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.m | |
// | |
#import <Foundation/Foundation.h> | |
#import "NSObject+Switch.h" | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
id str = @"Hello"; | |
[str switch:@{ | |
@"Hello": ^{ | |
NSLog(@"You said hello."); | |
}, | |
@"Goodbye": ^{ | |
NSLog(@"You said goodbye."); | |
} | |
} | |
default:^(id obj) { | |
NSLog(@"No case matches for %@", obj); | |
}]; | |
} | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSObject+Switch.h | |
// | |
#import <Foundation/Foundation.h> | |
@interface NSObject (Switch) | |
- (void)switch:(NSDictionary *)cases default:(void (^)(id obj))defaultBlock; | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSObject+Switch.m | |
// | |
#import "NSObject+Switch.h" | |
@implementation NSObject (Switch) | |
- (void)switch:(NSDictionary *)cases default:(void (^)(id obj))defaultBlock | |
{ | |
void (^block)(id) = [cases objectForKey:self]; | |
if (block != NULL) { | |
block(self); | |
} else { | |
defaultBlock(self); | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment