Swift Recursion: In this tutorial, you will learn to create a recursive function; a function that calls itself.
Swift Recursion is the process where a function calls, and the function which calls itself is know as recursive function.
A function that calls itself is known as a recursive function. Also, this method is known as recursion. While creating a recursive function, you should create a condition so the function doesn’t call itself indefinitely (limitlessly).
In this article, you will learn-
How recursion works in Swift?
func recurse() { //statements recurse() } recurse()
The figure underneath shows how recursion functions by calling itself again and again.
In the above flow chart, the recursion executes boundlessly. Nonetheless, almost the entirety of the occasions, you create a recursion that executes until some condition is met.
To forestall infinite recursion, use the recursive call inside the Swift Conditional Statements for example if…else statement.
Example 1: Print N positive numbers
func countDownToZero(num: Int) { print(num) if num > 0 { countDownToZero(num: num - 1) } } print("Countdown:") countDownToZero(num:3)
At the point when you run the accompanying project, the output will be:
Countdown: 3 2 1 0
In the above program, the statement print(“Countdown:”) outputs Countdown: in the console. Also, the statement countDownToZero(num:3) calls the function that takes a parameter Integer.
The statement inside the function countDownToZero() executes and if the condition num > 0 is met, the function countDownToZero() is called again as countDownToZero(num: num – 1).
On the off chance that condition isn’t met, the function call isn’t done and the recursion stops.
Let’s see this in steps
Execution steps |
Steps Function call Printed num > 0 ? |
1 countDownToZero(3) 3 Yes |
2 countDownToZero(2) 2 Yes |
3 countDownToZero(1) 1 Yes |
4 countDownToZero(0) 0 No (Ends) |
Example 2: Find factorial of a number
func factorial(of num: Int) -> Int { if num == 1 { return 1 } else { return num * factorial(of:num - 1) } } let x = 4 let result = factorial(of: x) print("The factorial of \(x) is \(result)")
At the point when you run the accompanying system, the output will be:
The factorial of 4 is 24
How this example works?
Let’s see this in steps
Execution steps |
Steps Argument passed 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 |
Generally recursion is used as a substitution of iteration when the solution for an issue can be find in around two stages. The initial step searches a solution, if not repeat the process.
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.