Skip to content

Instantly share code, notes, and snippets.

@azmfaridee
Created August 14, 2013 17:38
Show Gist options
  • Save azmfaridee/6233467 to your computer and use it in GitHub Desktop.
Save azmfaridee/6233467 to your computer and use it in GitHub Desktop.
A demonstration of using closures in Objective C. In Objective C terminology, it's called 'Blocks' instead of closures. Here I'm creating a 'block' that can create other 'blocks' by supplying a parameter. I run this in XCode 4.6 and Mac OS X 10.8. I had ARC turned on while I was coding this, but I think it's not a must for this particular exampl…
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
int (^(^makeAdder)(int))(int) = ^(int toAdd) {
int (^fn)(int) = ^(int arg) {
return toAdd + arg;
};
return fn;
};
int (^tenAdder)(int) = makeAdder(10);
int (^twentyAdder)(int) = makeAdder(20);
int arg = 3;
NSLog(@"Using tenAdder() with arg %d -> result : %d", arg, tenAdder(arg));
NSLog(@"Using twentyAdder() with arg %d -> result : %d", arg, twentyAdder(arg));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment