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
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.
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!
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With