O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Tail recursion

Tail recursion is a special case of recursion where the calling function does no more execution after making a recursive call to itself. In other words, a function is named tail recursive if its final expression is a recursive call. The previous recursion examples that we have been introduced to were not tail recursive functions.

To be able to understand tail recursion, we will develop the factorial function that we developed before with the tail recursion technique. Then we will talk about the differences:

func factorial(n: Int, currentFactorial: Int = 1) -> Int {     return n == 0 ? currentFactorial : factorial(n: n - 1,    currentFactorial: currentFactorial * n) } print(factorial(n: 3)) 

Note that we provide a default argument ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required