Tuples in Objective-C

Derrick Ho
1 min readMay 17, 2017

--

What do you mean Tuples? Objective-c has no tuples! Instead you should be using either an NSArray or an NSDictionary!

Sure, you can do that, but every now and then it’s nice to come up with a crazy alternative.

What alternative? well… using blocks.

- (void (^)(NSInteger *, NSString *__autoreleasing *))somethingThatReturnsATuple {
return ^(NSInteger *n, NSString **s){
*n = 8;
*s = @"welcome to tuple land";
};
}

This is an objective-c method that returns a block, or should I say “tuple”. It has all the necessary ingredients. This “tuple” is storing an NSInteger and an NSString. You can get values out of this tuple like so:

void(^tuple)(NSInteger *, NSString **) = [self somethingThatReturnsATuple];NSInteger num;
NSString *str;
tuple(&num, &str);NSLog(@"%ld", (long)num); // prints 8
NSLog(@"%@", str); // prints "welcome to tuple land"

--

--