Skip to content

Instantly share code, notes, and snippets.

@churchofthought
Last active December 16, 2015 19:39
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 churchofthought/5487095 to your computer and use it in GitHub Desktop.
Save churchofthought/5487095 to your computer and use it in GitHub Desktop.
Functional OR for Objective C.
#define __VA_NARGS__(...) (sizeof((id[]){__VA_ARGS__})/sizeof(id))
#define OR(...) or(__VA_NARGS__(__VA_ARGS__), __VA_ARGS__)
static inline id or(int numArgs, ...);
static inline BOOL isEmpty(id thing) {
return thing == nil
|| thing == [NSNull null]
|| ([thing respondsToSelector:@selector(length)]
&& [thing length] == 0)
|| ([thing respondsToSelector:@selector(count)]
&& [thing count] == 0);
}
static inline id or(int numArgs, ...)
{
id obj;
va_list args;
for (va_start(args, numArgs); numArgs; --numArgs)
if (!isEmpty(obj = va_arg(args, id))) break;
va_end(args);
return obj;
}
NSLog(@"%@", OR(nil,@"", @{@"foo": @"bar"}, @[]));
// outputs {foo = bar;}
NSLog(@"%@", OR(nil,@"", @{}, @[]));
// outputs []
NSLog(@"%@", OR(nil,@"", @[], @"", @{}));
// outputs {}
NSLog(@"%@", OR(nil,@"", @[], @"", nil));
// outputs (null)
NSLog(@"%@", OR(nil,@"", @[], @"", [NSNull null]));
// outputs <null>
NSLog(@"%@", OR(nil,[NSNull null], @[], @"", @"", @"woot"));
// outputs "woot"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment