Skip to content

Instantly share code, notes, and snippets.

@mhuusko5
Forked from CraigSiemens/iflet.m
Created November 12, 2015 18:37
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 mhuusko5/6c3637882473954038df to your computer and use it in GitHub Desktop.
Save mhuusko5/6c3637882473954038df to your computer and use it in GitHub Desktop.
if-let and guard macros for Objective C
#import <Foundation/Foundation.h>
// VARIABLE must be a variable declaration (NSString *foo)
// VALUE is what you are checking is not nil
// WHERE is an additional BOOL condition
#define iflet(VARIABLE, VALUE) \
ifletwhere(VARIABLE, VALUE, YES)
#define ifletwhere(VARIABLE, VALUE, WHERE) \
for (BOOL b_ = YES; b_ != NO;) \
for (id obj_ = (VALUE); b_ != NO;) \
for (VARIABLE = (obj_ ?: (VALUE)); b_ != NO; b_ = NO) \
if (obj_ != nil && (WHERE))
// Called just like the swift verstion
// guard(1 < 2) else {
// return
// }
#define guard(CONDITION) \
if (CONDITION) {}
#define guardletwhere(VARIABLE, VALUE, WHERE) \
ifletwhere(VARIABLE, VALUE, WHERE) {}
int main(int argc, char *argv[]) {
@autoreleasepool {
NSString *x = @"asdf";
NSString *y = nil;
iflet(NSString *z, x) {
NSLog(@"x is not nil");
}
iflet(NSString *z, y) {
NSLog(@"y is not nil");
}
else {
NSLog(@"y is nil");
}
ifletwhere(NSString *z, x, z.length < 100) {
NSLog(@"x is not nil and < 100");
}
guard(3 < 2) else {
NSLog(@"guard failed");
}
guardletwhere(NSString *z, x, z.length < 3) else {
NSLog(@"guardletwhere failed");
}
}
}
/* outputs:
iflet[57328:5182484] x is not nil
iflet[57328:5182484] y is nil
iflet[57328:5182484] x is not nil and < 100
iflet[57328:5182484] guard failed
iflet[57328:5182484] guardletwhere failed
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment