Last active
December 8, 2017 00:49
-
-
Save ksoftllc/99ed79a19da1316e9b47dec7d55946cc to your computer and use it in GitHub Desktop.
Switch on NSString in Objective-C
This file contains 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
//NOTE: split into 2 files | |
//Based on/inspired by this stackoverflow.com post: https://stackoverflow.com/a/10177956/1256015 by Graham Perks. | |
//------ Switcher.h | |
/** | |
Example usage: | |
@code | |
NSString * someString = @"Hearts"; | |
[Switcher switchOnString:someString | |
using:@{ | |
@"Spades": | |
^{ | |
NSLog(@"Spades block"); | |
}, | |
@"Hearts": | |
^{ | |
NSLog(@"Hearts block"); | |
}, | |
@"Clubs": | |
^{ | |
NSLog(@"Clubs block"); | |
}, | |
@"Diamonds": | |
^{ | |
NSLog(@"Diamonds block"); | |
} | |
} withDefault: | |
^{ | |
NSLog(@"Default block"); | |
} | |
]; | |
@endcode | |
*/ | |
typedef void (^CaseBlock)(); | |
@interface Switcher : NSObject | |
+ (void)switchOnString:(NSString *)tString | |
using:(NSDictionary<NSString *, CaseBlock> *)tCases | |
withDefault:(CaseBlock)tDefaultBlock; | |
@end | |
//------ Switcher.m | |
@implementation Switcher | |
+ (void)switchOnString:(NSString *)tString | |
using:(NSDictionary<NSString *, CaseBlock> *)tCases | |
withDefault:(CaseBlock)tDefaultBlock { | |
CaseBlock blockToExecute = tCases[tString]; | |
if (blockToExecute) { | |
blockToExecute(); | |
} else { | |
tDefaultBlock(); | |
} | |
} | |
@end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
While Objective-C doesn't have a switch statement for NSString, this snippet allows you to use a dictionary where the NSString key looks up a code block to execute. Even lays out much like a switch statement. See the example code in the comment block.