Skip to content

Instantly share code, notes, and snippets.

@wjlafrance
Created April 4, 2013 23:59
Show Gist options
  • Save wjlafrance/5315490 to your computer and use it in GitHub Desktop.
Save wjlafrance/5315490 to your computer and use it in GitHub Desktop.
Switching on objects
//
// 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;
}
//
// NSObject+Switch.h
//
#import <Foundation/Foundation.h>
@interface NSObject (Switch)
- (void)switch:(NSDictionary *)cases default:(void (^)(id obj))defaultBlock;
@end
//
// 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