Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested recursive function in swift

I'm trying to do a nested recursive function but when I compile, the compiler crash (Segmentation fault).

Here is my code :

func test()
{
    func inner(val : Int)
    {
        println("\(val)")
        if val > 0
        {
           inner(val - 1)
        }
    }
    inner(3)
}

And the compiler logs are here

like image 484
Morniak Avatar asked Jun 17 '14 18:06

Morniak


People also ask

Does Swift support recursion?

Swift uses tail recursion optimisation which means that if the method call in the recursive function is located at the end of the function, the compiler is able to use jump statements instead of method calls. This means that calls to itself in the recursion do not add to the call stack.

Can a function call itself Swift?

In essence, a recursion happens when a thing is defined in terms of itself or its type. And in Swift, recursion means that a function calls itself!

How do you stop a recursive function in Swift?

Stopping Condition for Recursion We use the if...else statement (or similar approach) to break the recursion. Normally, a recursive function has two branches: One for recursive calls.


1 Answers

interesting... it seems like maybe it's bailing when trying to capture a reference to inner before it has been defined?

the following fixes it for us:

func test() {
    var inner: (Int) -> () = { _ in }    // give it a no-op definition
    inner = { val in
        println("\(val)")
        if val > 0 {
            inner(val - 1)
        }
    }
    inner(3)
}

of course without the nesting we don't have any issues at all, e.g. the following works completely as expected:

func test(val: Int) {
    println("\(val)")
    if val > 0 {
        test(val - 1)
    }
}
test(3)

I'd say: report it!

like image 158
fqdn Avatar answered Sep 26 '22 02:09

fqdn