Recursion in Swift

Our example demonstrates recursive functions in Swift. Here’s a classic implementation of factorial calculation using recursion.

import Foundation

// This `fact` function calls itself until it reaches the
// base case of `fact(0)`.
func fact(_ n: Int) -> Int {
    if n == 0 {
        return 1
    }
    return n * fact(n - 1)
}

// Main function equivalent in Swift
func main() {
    print(fact(7))

    // Closures can also be recursive in Swift, but we need to declare
    // the variable before defining the closure to allow recursion
    var fib: ((Int) -> Int)!
    
    fib = { n in
        if n < 2 {
            return n
        }
        
        // Since `fib` was previously declared, Swift
        // knows which function to call with `fib` here.
        return fib(n - 1) + fib(n - 2)
    }
    
    print(fib(7))
}

// Call the main function
main()

To run the program, save it as recursion.swift and use the Swift compiler:

$ swift recursion.swift
5040
13

This example demonstrates two types of recursion in Swift:

  1. A traditional recursive function (fact) that calculates the factorial of a number.
  2. A recursive closure (fib) that calculates Fibonacci numbers.

The fact function is straightforward: it calls itself with n-1 until it reaches the base case of 0.

The fib closure is more complex. In Swift, to create a recursive closure, we need to declare the variable before defining the closure. This allows the closure to reference itself inside its own body.

Both functions are called in the main function, which serves as the entry point of our program.

Swift’s powerful type inference and functional programming features make it well-suited for recursive algorithms, providing a clean and expressive syntax for these kinds of problems.