Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Recursive Functions in Swift
Written by Team Kodeco

A recursive function is a function that calls itself. Recursive functions are used to solve problems that can be broken down into smaller, identical subproblems. A common example of a problem that can be solved using recursion is computing the factorial of a number.

// function to compute factorial of a number
func factorial(of number: Int) -> Int {
  if number == 0 {
    return 1
  }
  return number * factorial(of: number - 1)
}

print(factorial(of: 5)) // 120

A factorial is a mathematical operation that is the product of all positive integers less than or equal to n. For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120.

This function uses recursion to calculate the factorial of a given number. It starts with the input number, and in each recursive step it decrements the input number by 1 and multiplies it with the result of the function called with the new decremented number. This process continues until the input number reaches 0, resulting in the factorial of the original input number.

When writing recursive functions, it’s important to include a base case. The base case is the point at which the function stops calling itself. In the example above, the base case is when the number passed to the function is 0. If there is no base case, the function will continue to call itself indefinitely, resulting in a stack overflow.

Recursive functions can be an elegant way to solve problems that can be broken down into smaller identical subproblems, but they can also be difficult to understand. It’s important to test and debug them thoroughly to ensure that they’re working as expected.

Note: Be careful with the recursion depth. If the recursion goes too deep, the program will run out of stack space and crash.

© 2024 Kodeco Inc.