how to make a recursive function in swift

Here is an example of a recursive function in Swift. The function calculates the factorial of a given number:

main.swift
func factorial(_ n: Int) -> Int {
   if n == 0 {
      return 1
   } else {
      return n * factorial(n - 1)
   }
}
117 chars
8 lines

This function calls itself with a smaller value of n until the base case of n == 0 is reached. The base case stops the recursion and allows the function to start returning values back up the call stack.

gistlibby LogSnag