Recursion in Swift with example
Recursion in Swift
Recursion in Swift involves a function calling itself to solve a problem. A recursive function typically consists of two main parts:
- Base Case: This is the condition that stops the recursion. Without a base case, a recursive function would call itself indefinitely, leading to a stack overflow.
- Recursive Step: This is where the function calls itself with a modified input, moving closer to the base case.
Example: Calculating Factorial using Recursion
func factorial(number: Int) -> Int {
// Base case: If number is 0 or 1, return 1
if number == 0 || number == 1 {
return 1
}
// Recursive step: Call factorial with (number - 1)
else {
return number * factorial(number: number - 1)
}
}
// Example:
let num = 5
let result = factorial(number: num)
print("The factorial of \(num) is: \(result)")
Output:
The factorial of 5 is: 120