12

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

Morniak
  • 958
  • 1
  • 12
  • 37
  • 1
    looks like a bug to me – Christian Dietrich Jun 17 '14 at 18:22
  • 1
    Yes, file a bug report, compilers shouldn't crash :p – Jack Jun 17 '14 at 18:26
  • I know that the compiler shouldn't crash but as it's a beta, syntax errors can provoque this kind of error. My question is : is there any syntax error in my code ? Is there something like the `rec` keyword in OCaml ? – Morniak Jun 17 '14 at 18:34
  • 2
    GOOD NEWS! it looks like this has been fixed in Swift2 - drop the original code (above) into a playground in Xcode 7 beta and call the `test()` function, works as expected! :) – fqdn Jun 28 '15 at 16:54

1 Answers1

19

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!

fqdn
  • 2,823
  • 1
  • 13
  • 16