English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
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.
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.
Step | Function call | num > 0 ? | |
---|---|---|---|
1 | countDownToZero(3) | 3 | Yes |
2 | countDownToZero(2) | 2 | Yes |
3 | countDownToZero(1) | 1 | Yes |
4 | countDownToZero(0) | 0 | No (End) |
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
Step | Passed Parameter | Return Statement | Value |
---|---|---|---|
1 | 4 | return 4 * factorial(of:3) | 4 * factorial(of:3) |
2 | 3 | return 3 * factorial(of:2) | 4 *3 * factorial(of:2) |
3 | 2 | return 2 * factorial(of:1) | 4 * 3 *2 * factorial(of:1) |
4 | 1 | return 1 | 4 * 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.