Tuesday, June 23, 2015

Objective -c Tuple


Objective - c does not have native support for Tuples.  However, in most cases an NSArray will suffice.  The difference between a tuple and an array is mostly one of categorization.  Tuples are for bundling things that don't have uniformity while Arrays are expected to have the same type.  With that said, a Tuple can be implemented by using an Array, but with it's array features hidden away.

Below is my implantation for a Tuple by using Blocks and variadic function.

typedef id(^TupleType)(NSInteger);
TupleType Tuple(id obj, ...) NS_REQUIRES_NIL_TERMINATION;
TupleType Tuple(id obj, ...) {
va_list argList;
va_start(argList, obj);
NSMutableArray *mut = [NSMutableArray new];
for (; obj; obj = va_arg(argList, id)){
[mut addObject:obj];
}
va_end(argList);
return ^(NSInteger index){
return index >= mut.count ? nil : mut[index];
};
}

You can use it like this

TupleType t = Tuple([MYObj new], [MYObj new], [MYObj new], nil);
for (int i = 0; i < 3; ++i) 
{
NSLog(@"%@", t(i));
}

No comments:

Post a Comment