How to implement Recursion in Swift

Algorithms Computer Science Recursion Swift

29 Oct 2020 . 2 min read       @gurjitpt


In Computer Science, recursive function is a function that calls itself to solve problem and this technique is called recursion. Almost all programming languages support recursion and Swift programming language is one of them.

In this article, you will learn how to implement recursion in Swift programming language.

A recursive function can have one or more inputs to produce result and it must have base case to avoid calling itself infinitely. The first is a "base case" that breaks the recursion and the second case is a "recursive case". Let's see how we can implement recursion in Swift.

First of all, create function called recursive with one parameter input with type Int and it has return type of Int also.

func recursive(input: Int) -> Int { }

Now we will create "base case" for recursion. In base case, if input is less than or equals to 0 it will return input.

if input <= 0 {
    return input
}

Now it's time to implement "recursive case". In recursive case function will call itself.

else {
    return recursive(input: input - 1)
}

Final code


import UIKit
func recursive(input: Int) -> Int {
    print(input)
    if input <= 0 {
       return input
    } else {
       return recursive(input: input - 1)
    }
}
recursive(input: 4)

Output


4
3
2
1
0

Conclusion

In computer science, recursive approach can solve many problems and these problems can be solved by iteration. These are the basic fundamentals of computer science. Its always beneficial to know for interview purpose that how we can implement recursion.

Thanks!


Next Posts

Implement Binary Search in Swift

In computer science, there are two types of algorithms commonly used to solve a problem searching and sorting algorithms. Its valuable to know which algorithm to use to perform a ..

Sep 14, 2020 . 2 min read     Algorithms

Read More »

Protocol Extensions in Swift Empty space for void

A protocol can defines a set of methods that can be adopted by any class, but we can’t write code inside.On the other hand, extensions gives us the power to write code inside methods..

May 01, 2020 . 1 min read     Swift

Read More »

Difference between Struct and Classes explained in Swift

Structures and Classes are basic templates for any application which consists of properties and methods implements for behaviour .You can define structure or class..

May 06, 2020 . 2 min read     Swift

Read More »