Skip to content

Instantly share code, notes, and snippets.

@Arthraim
Last active August 29, 2015 14:23
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 Arthraim/f2cbee055b88421a9106 to your computer and use it in GitHub Desktop.
Save Arthraim/f2cbee055b88421a9106 to your computer and use it in GitHub Desktop.
Tryable NSDictionary

Can I do something like this?

@implementation NSObject (Tryable)

- (id)tryWithKey:(id)key {
    if (!self) return [NSNull null];
    if (![self isKindOfClass:NSDictionary.class]) return [NSNull null];
    if (![(NSDictionary *)self objectForKey:key]
        || [(NSDictionary *)self objectForKey:key] == [NSNull null]) {
        return [NSNull null];
    }
    return ((NSDictionary *)self)[key];
}

@end

Thus, when I handling NSDictionary, I can just ...

id whatIWant = [[[dict tryWithKey:@"aaa"] tryWithKey:@"bbb"] tryWithKey:@"ccc"];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment