Recursion in Swift
Our example demonstrates recursive functions in Swift. Here’s a classic implementation of factorial calculation using recursion.
To run the program, save it as recursion.swift
and use the Swift compiler:
This example demonstrates two types of recursion in Swift:
- A traditional recursive function (
fact
) that calculates the factorial of a number. - 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.