3

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.

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I must have missed or skimmed the section on inout parameters. I even tried AutoreleasingUnsafeMutablePointer<Int> and UnsafeMutablePointer<Int>, but that led me down a path of sorrow :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.