Last active
December 16, 2015 19:39
-
-
Save churchofthought/5487095 to your computer and use it in GitHub Desktop.
Functional OR for Objective C.
This file contains 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
#define __VA_NARGS__(...) (sizeof((id[]){__VA_ARGS__})/sizeof(id)) | |
#define OR(...) or(__VA_NARGS__(__VA_ARGS__), __VA_ARGS__) | |
static inline id or(int numArgs, ...); |
This file contains 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
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; | |
} |
This file contains 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
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