Skip to content

Instantly share code, notes, and snippets.



Last active Jan 7, 2016
What would you like to do?
if-let in ObjC
#import <Foundation/Foundation.h>
#define iflet(LHS, RHS) \
for (id obj_ = (RHS); obj_ != nil;) \
for (LHS = (obj_ ?: (RHS)); obj_ != nil; obj_ = nil)
int main(int argc, char *argv[]) {
@autoreleasepool {
NSString *x = nil;
NSString *y = @"y";
iflet(NSString *z, x) {
NSLog(@"x is non-nil: %@", z);
iflet(NSString *z, y) {
NSLog(@"y is non-nil: %@", z);
/* outputs:
Untitled[44105:2794964] y is non-nil: y

This comment has been minimized.

Copy link
Owner Author

@cdzombak cdzombak commented Feb 26, 2015


This comment has been minimized.

Copy link

@CraigSiemens CraigSiemens commented Aug 18, 2015

Do you have a way to add an else case? This is what I came up with and it seems to work but I'm not sure if I overlooked anything.

#define iflet(LHS, RHS) \
    for (BOOL b_ = YES; b_ != NO;) \
        for (id obj_ = (RHS); b_ != NO;) \
            for (LHS = (obj_ ?: (RHS)); b_ != NO; b_ = NO) \
                if (obj_ != nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment