Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's Objective-C's equivalent of Swift's inout Parameters?

I'm back on writing Objective-C code again and is trying to find the equivalent of Swift's inout parameter notation in Objective-C.

func swapTwoInts(_ a: inout Int, _ b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html#//apple_ref/doc/uid/TP40014097-CH10-ID158

So far I've learned: 1.inout is not objc-compatible. 2.objc simply doesn't have language feature like this.

However, when I'm designing my API, I want it to be clear that this method is modifying its parameter. Is there any good way to accomplish this in Objective-C? Thank you!

like image 618
CeliaLi Avatar asked Jul 05 '17 08:07

CeliaLi


1 Answers

For bridging between obj-c and swift, you can put your params in a class and pass that in: https://stackoverflow.com/a/26288083/78496

You can sort of do inout in Obj-C, you just don't see it very often.

- (void) doThing: (int *) varA andAnother:(int *) varB
{
    int temp = *varA;
    *varA = *varB;
    *varB = temp;
}

Then you'd call it using & to pass a reference

int i = 1;
int j = 2;
[self doThing:&i andAnother:&j]
like image 151
chedabob Avatar answered Sep 22 '22 02:09

chedabob