Skip to content

Instantly share code, notes, and snippets.

@ksoftllc
Last active December 8, 2017 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ksoftllc/99ed79a19da1316e9b47dec7d55946cc to your computer and use it in GitHub Desktop.
Save ksoftllc/99ed79a19da1316e9b47dec7d55946cc to your computer and use it in GitHub Desktop.
Switch on NSString in Objective-C
//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
@ksoftllc
Copy link
Author

ksoftllc commented Dec 8, 2017

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment