Multiple Return Values in Objective-C

Objective-C has support for multiple return values through the use of structures or tuples. This feature can be used to return both result and error values from a function.

#import <Foundation/Foundation.h>

// Define a structure to hold multiple return values
typedef struct {
    int first;
    int second;
} IntPair;

// This function returns a structure containing two integers
IntPair vals() {
    return (IntPair){3, 7};
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // Here we use the structure to get multiple return values
        IntPair result = vals();
        NSLog(@"%d", result.first);
        NSLog(@"%d", result.second);
        
        // If you only want a subset of the returned values,
        // you can simply ignore the ones you don't need
        IntPair partialResult = vals();
        NSLog(@"%d", partialResult.second);
    }
    return 0;
}

To run the program, save it as MultipleReturnValues.m and compile it using:

$ clang -framework Foundation MultipleReturnValues.m -o MultipleReturnValues
$ ./MultipleReturnValues
3
7
7

In Objective-C, we don’t have built-in support for multiple return values like in some other languages. Instead, we use a structure (IntPair in this case) to return multiple values. The vals() function returns an IntPair structure containing two integers.

In the main function, we call vals() and store the result in an IntPair structure. We can then access the individual values using the dot notation (result.first and result.second).

If you only need a subset of the returned values, you can simply ignore the ones you don’t need. Unlike some languages that have a specific syntax for this (like the blank identifier _), in Objective-C you just don’t use the value you don’t need.

This approach of using structures for multiple return values is common in Objective-C and C. In more complex scenarios, you might use Objective-C objects or even pass pointers to variables that the function will fill in.

Accepting a variable number of arguments is another feature available in Objective-C; we’ll look at this in a future example.