Skip to content

Instantly share code, notes, and snippets.

@tewha
Last active December 25, 2015 08:09
Show Gist options
  • Save tewha/6944910 to your computer and use it in GitHub Desktop.
Save tewha/6944910 to your computer and use it in GitHub Desktop.
Inspired by NSDictionaryOfVariableBindings.
#define DictionaryOfEnumBindings(...) DictionaryOfEnumBindingsWorker(@"" # __VA_ARGS__, __VA_ARGS__, nil)
NSDictionary *DictionaryOfEnumBindingsWorker(NSString *commaSeparatedKeysString, int firstValue, ...) {
NSMutableDictionary *enums = [NSMutableDictionary dictionary];
NSMutableArray *names = [[commaSeparatedKeysString componentsSeparatedByString:@","] mutableCopy];
va_list ap;
va_start(ap, firstValue);
NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *firstPaddedName = [names objectAtIndex:0];
enums[@(firstValue)] = [firstPaddedName stringByTrimmingCharactersInSet:whiteSpace];
[names removeObjectAtIndex:0];
for (NSString *paddedName in names) {
int value = va_arg(ap, int);
enums[@(value)] = [paddedName stringByTrimmingCharactersInSet:whiteSpace];
}
va_end(ap);
return [enums copy];
}
@tewha
Copy link
Author

tewha commented Oct 12, 2013

Use:

NSDictionary *enumNames = DictionaryOfEnumBindings(NSTextAlignmentLeft, NSTextAlignmentCenter, NSTextAlignmentRight);

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