Last active
December 20, 2015 05:59
-
-
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.
This file contains hidden or 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
- (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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How about modifying this to use dictionary syntax in the block: