Morniak
Morniak

Reputation: 998

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

Upvotes: 12

Views: 7326

Answers (1)

fqdn
fqdn

Reputation: 2843

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!

Upvotes: 19

Related Questions