Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return two values?

I'd like to return a Cartesian coordinate (x, y), as two ints. The only way I see is to create a class and return an instance of it.

How to return two values from a method in Objective C?

like image 922
nickthedude Avatar asked Jan 04 '10 22:01

nickthedude


People also ask

How can I return two values from a function?

We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data. So we have to pass the address of the data.

Can you return 2 values in Java?

You can return only one value in Java. If needed you can return multiple values using array or an object.

Can you return 2 values in Python?

Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.

Can we return two values in C?

No, you can not return multiple values like this in C. A function can have at most one single return value.


4 Answers

You can only return one value from a function (just like C), but the value can be anything, including a struct. And since you can return a struct by value, you can define a function like this (to borrow your example):

-(NSPoint)scalePoint:(NSPoint)pt by:(float)scale
{
    return NSMakePoint(pt.x*scale, pt.y*scale);
}

This is only really appropriate for small/simple structs.

If you want to return more than one new object, your function should take pointers to the object pointer, thus:

-(void)mungeFirst:(NSString**)stringOne andSecond:(NSString**)stringTwo
{
    *stringOne = [NSString stringWithString:@"foo"];
    *stringTwo = [NSString stringWithString:@"baz"];
}
like image 151
gavinb Avatar answered Oct 21 '22 14:10

gavinb


Couldn't you make an NSArray for this?

return [NSArray arrayWithObjects:coorX, coorY, nil];
like image 39
Chris Long Avatar answered Oct 21 '22 15:10

Chris Long


You can either return one value directly and return another by reference, as shown in gs's answer, or create a struct type and return that. For example, Cocoa already includes a type to identify points on a 2D plane, NSPoint.

like image 32
Chuck Avatar answered Oct 21 '22 13:10

Chuck


I recommend you to return an NSDictionary, inside Dictionary you can store and send any object type and any number of variables.

-(NSDictionary*)calculateWith:(id)arg
{
NSDictionary *urDictionary =@{@"key1":value1,@"Key2":value2,.....};
return  urDictionary;
}
like image 33
Jeba Moses Avatar answered Oct 21 '22 13:10

Jeba Moses