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.
To run the program, save it as MultipleReturnValues.m
and compile it using:
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.