Search code examples
swiftfunctional-programming

Tail Recursion (Tail Call Optimization) in Swift 4


I tried to do the following simple function in Swift:

 func sum (n: Int, currentSum: Int = 0) -> Int {
    return n == 0 ? currentSum :
                    sum(n: n-1,
                        currentSum: currentSum + n)
 }

I expected that the compiler would use tail recursion optimization. But I fall into a (literally :-P) stack overflow problem.

Is there any flag I need to set to make the compiler do such optimization, I made any mistake on my code or this compiler optimization is not available?

Thanks!


Solution

  • As Martin notes, you won't get TCO in any case unless you turn on the optimizer (-O), but even in that case, there's no way to guarantee that you'll get TCO, and so you really can't rely on it. Swift is not particularly friendly to recursive algorithms. Typically you'd write this as:

    func sum(n: Int) -> Int {
        return (1...n).reduce(0, +)    
    }
    

    Or to maintain the same computational pattern (i.e. counting down from n to 1):

    func sum(n: Int) -> Int {
        return (1...n).reversed().reduce(0, +)
    }