English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Swift Recursion

In this article, you will learn to create recursive functions. A self-calling function.

Calling itselfFunctionCalled recursive function. And, this technique is called recursion. When creating a recursive function, you must create conditions so that the function does not call itself indefinitely.

How does recursion work in Swift?

func recurse() {
    //statements
    recurse()
}
recurse()

The following figure shows the way of recursive calls.

In the above flowchart, recursion is executed infinitely. In some cases, you may need to create a recursion that will continue to execute until certain conditions are met.

To prevent infinite recursion, use recursive calls within Swift conditional statements, for exampleif ... else statement.

Example1Print N positive numbers

func countDownToZero(num: Int) {
    print(num)
    if num > 0 {
        countDownToZero(num: num - 1)
    }
}
print("Countdown:")
countDownToZero(num:3)

When you run the following program, the output will be:

Countdown:
3
2
1
0

In the above program, the statement print("Countdown:") outputs to the consoleCountdown:This statement calls the function countDownToZero(num: with an Integer type parameter3).

countDownToZero() executes the statements inside the function, if the condition num > 0 is met, countDownToZero() calls the function countDownToZero(num: num again - 1).

If the condition is not met, do not execute the function call and stop the recursion.

Let's take a look at the specific steps

Execution Step
StepFunction callPrintnum > 0 ?
1countDownToZero(3)3Yes
2countDownToZero(2)2Yes
3countDownToZero(1)1Yes
4countDownToZero(0)0No (End)

Example2Find the factorial of a number

func factorial(of num: Int) -> Int
    if num == 1 {
        return 1
    }
        return num * factorial(of:num - 1)
    }
}
let x = 4
let result = factorial(of: x)
print("The factorial of \(x) is \(result)")

When you run the following program, the output will be:

The factorial of 4 is 24

How does this instance work?

Let's look at it step by step

Execution Step
StepPassed ParameterReturn StatementValue
14return 4 * factorial(of:3)4 * factorial(of:3)
23return 3 * factorial(of:2)4 *3 * factorial(of:2)
32return 2 * factorial(of:1)4 * 3 *2 * factorial(of:1)
41return 14 * 3 * 2 * 1

When a solution to a problem can be found in about two steps, recursion is often used as a replacement for iteration.