Skip to content

Instantly share code, notes, and snippets.

@Pretz
Last active December 20, 2015 05:59
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 Pretz/6082744 to your computer and use it in GitHub Desktop.
Save Pretz/6082744 to your computer and use it in GitHub Desktop.
draft of a dictionary comprehension idea for obj-c: generating dictionaries over collections using simple-ish block syntax.
- (NSDictionary *)dictionaryOfPeople:(NSArray *)people {
return [people dictionaryViaEnumeration:^(Person *person, id *key, id *value) {
*key = person.identifier;
*value = person.name;
}];
}
////////////////////
typedef void (^TransformBlock)(id obj, id *key, id *value);
@implementation NSObject (DictionaryGenerator)
- (NSDictionary *)dictionaryViaEnumeration:(TransformBlock)block {
NSAssert([self conformsToProtocol:@protocol(NSFastEnumeration)], @"dictionaryViaEnumeration only works on objects conforming to NSFastEnumeration");
NSInteger count = 0;
if ([self respondsToSelector:@selector(count)]) {
count = [(id)self count];
} else if ([self respondsToSelector:@selector(length)]) {
count = [(id)self length];
}
NSMutableDictionary *result = [NSMutableDictionary dictionaryWithCapacity:count];
for (id object in (id<NSFastEnumeration>)self) {
id key = nil;
id value = nil;
block(object, &key, &value);
if (!value) {
value = [NSNull null];
}
if (key) {
result[key] = value;
}
}
return result;
}
@end
@neilgall
Copy link

How about modifying this to use dictionary syntax in the block:

- (NSDictionary *)dictionaryOfPeople:(NSArray *)people {
    return [people dictionaryViaEnumeration:^NSDictionary *(Person *person) {
        return @{ person.identifier : person.name };
    }];
}

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