Skip to content

Instantly share code, notes, and snippets.

@axelarge
Last active December 19, 2015 17:19
Show Gist options
  • Save axelarge/5990587 to your computer and use it in GitHub Desktop.
Save axelarge/5990587 to your computer and use it in GitHub Desktop.
Objective-C macro for switching on objects
@implementation NSObject (Extra)
- (BOOL)isEqualToAnyOf:(id)object, ...
{
va_list args;
va_start(args, object);
for (id other = object; other != nil; other = va_arg(args, id)) {
if ([self isEqual:other]) return YES;
}
va_end(args);
return NO;
}
@end
#define SWITCH(object, ...) { \
id ___switch_object = object; \
BOOL ___switch_stop = NO; \
do __VA_ARGS__ while(0); \
}
#define CASE(...) \
if (___switch_stop) break; \
if ([___switch_object isEqualToAnyOf:__VA_ARGS__, nil] && (___switch_stop = YES))
#define DEFAULT \
if (___switch_stop) break;
void Test(NSString *string) {
SWITCH(string, {
CASE(@"Great success") {
// Switch cases auto-break so you don't have to
}
CASE(@"Returning from inside a case works just fine") {
return;
}
CASE(@"I", @"like", @"turtles") // Match on any of the passed
// Single statements can be left without braces
thatsCool();
DEFAULT {
NSLog(@"Default case reached");
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment