Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to pointer parameter in Swift function

How do you do pointers to pointers in Swift? In Objective-C I had a function which I would call recursively so that I could keep track of the number of recursions, but I'm stumped as to how to achieve this in Swift.

NSNumber *recursionCount = [NSNumber numberWithInteger:-1];
[self doRecursion:&recursionCount];

- (void)doRecursion:(NSNumber **)recursionCount {
    // I'm sure this is a terrible way to increment, but I have limited Objective-C experience
    // and this worked, so I moved on after failing to find a decent var++ equivalent :-(
    int addThis = (int)i + 1;
    *recursionCount = [NSNumber numberWithInt:[*recursionCount intValue] + addThis];
    [self doRecursion:recursionCount];
}

In the process of cutting this sample down for this post, I've ended up creating a never-ending loop, but you get the idea on how I'm remembering the value with each recursion.

Does anybody know how to do this in Swift? Thanks.

like image 365
Rainier Wolfcastle Avatar asked Jun 13 '26 06:06

Rainier Wolfcastle


1 Answers

Usage of pointers in swift is highly discouraged.

To change a variable passed as argument to a function, you have to pass it by reference (similar to passing its pointer) using the inout modifier. I've changed the logic of your function to stop after 10 iterations:

func doRecursion(inout recursionCount: Int) -> Int {
    if (recursionCount < 10) {
        ++recursionCount
         doRecursion(&recursionCount)
    }

    return recursionCount
}

Then you can call using:

var counter: Int = -1
let x = doRecursion(&counter) // Prints 10 in playground

Suggested reading: In-Out Parameters

like image 132
Antonio Avatar answered Jun 14 '26 23:06

Antonio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!