Swift Recursion
The function that calls itself is known as the Recursive function, and this technique is known as the Recursion.
If you want to learn more about the recursive function, follow these articles, Recursion and Types of Recursion.
Example
Here the recursive() function is calling itself again and again. Hence it is a recursive function.
WorkFlow of the Swift Recursion
The workflow of the Swift Recursion is given below:
Termination of the Swift Recursion
If we don’t mention any termination condition inside the recursive function, it will become an infinite loop. You have to have some termination condition inside the Swift recursive function.
Normally we use the if..else statement for breaking the loop condition.
Example
Example: Find Factorial of a Number
Let’s now understand the whole concept of the Swift recursion by giving an example.
The problem is that we want to find out the factorial of a number using Swift recursion.
If you want to learn about the problem and its solution, you can refer to this article Factorial Program in Java.
Implementation(in Swift)
func fact(num: Int) -> Int {
// Terminating condition
if num == 0 {
return 1
}
// calling the factorial function
return num * factorial(num: num - 1)
}
var number = 6
// calling the fact function
var result = fact(num: number)
print("The factorial of 6 is", result)
Output
Working Flow of the Program
The working flow of the program is shown below:
Frequently Asked Questions
What is Swift in iOS Development?
Swift is a robust, intuitive and powerful open language created by Apple that is used to build powerful apps for IOS, MAC, Apple Watch and Apple TV.
Is iOS written in Swift?
Most modern iOS apps are written and developed using Swift.
What languages does Swift use?
Swift has taken references from programming languages including Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and a few more that can be added to the list.
What are the best uses of the Swift?
The best uses of the Swift include building apps for iOS, Mac, Apple TV and Apple Watch.
Conclusion
In this article, we have extensively discussed the Recursion in Swift.
We started with the basic introduction, then we discussed,
- What Swift is
- What is the Swift Recursion
- Termination Condition of the recursion
-
Lastly, we gave the example of the factorial program.
We hope that this blog has helped you enhance your knowledge regarding Recursion in Swift and if you would like to learn more, check out our articles on The Definitive Swift Tutorial. Do upvote our blog to help other ninjas grow.
Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, interview bundle, follow guided paths for placement preparations and much more.!
Happy Reading!