In this blog, we are going to learn about recursion and how Swift Recursion works in swift with the help of an example.
First of all, I want to tell you about the recursion. The function that calls itself is known as the recursion function.
The working of the recursion function
The recursion function works in two cases.
1. To call the recursion function.
2. Stopping condition
Note:
If we do not put any break condition then the recursive function continuously calls itself infinitely.
We need to use any (if…else) similar type of approach to breaking the condition.
Advantages of Recursion
It makes code shorter and cleaner
Mainly used in graph and tree traversal.
Disadvantages of Recursion
Debugging is not easy as compared to the iterator program.
Takes more stack space.
Takes more time in processing.
Now lets us understand Swift Recusrion with a simple example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //Calling function count(input:3) // Do any additional setup after loading the view. } func count(input: Int) { // display the input print(input) // condition to break recursion if input == 0 { print("Stops") } // condition for recursion call else { // decrease the input value count(input: input - 1) } } } |
Output Image
Conclusion
I hope this blog helps you to understand the Swift Recursion.
Thanks for reading !!
For more blogs click here