How to return two values?

前端 未结 4 2213
深忆病人
深忆病人 2021-02-13 10:05

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 value

4条回答
  •  萌比男神i
    2021-02-13 10:36

    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"];
    }
    

提交回复
热议问题