Swift – Reverse String using Recursion
In this tutorial, we will learn how to reverse a string using recursion in Swift. We will understand the concept of recursion, write an algorithm, and implement it step by step with a complete Swift program and output.
What is Recursion?
Recursion is a technique in which a function calls itself to solve smaller subproblems of a larger problem. It is widely used in algorithms where problems can be divided into similar subproblems. A recursive function must have:
- A base case that stops the recursion.
- A recursive case that reduces the problem size and calls itself.
To reverse a string recursively, we can divide the problem into smaller parts and work on the first character and the rest of the string recursively.
Algorithm to Reverse a String Using Recursion
- Take the string as input.
- Base Case: If the string is empty or has one character, return the string itself.
- Recursive Case:
- Take the first character of the string.
- Reverse the rest of the string by recursively calling the function.
- Append the first character to the reversed substring.
This algorithm ensures that the string is broken down into smaller parts until the base case is reached.
Step-by-Step Implementation in Swift
1. Define the Base Case
Create a function that returns the string itself when its length is 0 or 1:
func reverseString(_ str: String) -> String {
if str.count <= 1 {
return str // Base case: return the string if it's empty or has one character
}
return "" // Placeholder for the recursive case
}
2. Add the Recursive Case
Implement the logic to reverse the string by appending the first character to the reversed substring:
func reverseString(_ str: String) -> String {
if str.count <= 1 {
return str // Base case
}
let firstChar = String(str.first!) // Get the first character
let restOfString = String(str.dropFirst()) // Get the rest of the string
return reverseString(restOfString) + firstChar // Recursive call
}
Explanation:
if str.count <= 1
: Stops the recursion when the string is empty or has one character.
String(str.first!)
: Extracts the first character of the string.
String(str.dropFirst())
: Removes the first character from the string.
reverseString(restOfString) + firstChar
: Recursively reverses the rest of the string and appends the first character at the end.
3. Test the Function
Let’s test the function with some example inputs:
// Test cases
print("Reversed 'hello': \(reverseString("hello"))") // Output: "olleh"
print("Reversed 'Swift': \(reverseString("Swift"))") // Output: "tfiwS"
print("Reversed 'A': \(reverseString("A"))") // Output: "A"
print("Reversed '': \(reverseString(""))") // Output: ""
Complete Swift Program
Here’s the complete Swift program:
import Foundation
// Recursive function to reverse a string
func reverseString(_ str: String) -> String {
if str.count <= 1 {
return str // Base case
}
let firstChar = String(str.first!) // Get the first character
let restOfString = String(str.dropFirst()) // Get the rest of the string
return reverseString(restOfString) + firstChar // Recursive call
}
// Test cases
print("Reversed 'hello': \(reverseString("hello"))") // Output: "olleh"
print("Reversed 'Swift': \(reverseString("Swift"))") // Output: "tfiwS"
print("Reversed 'A': \(reverseString("A"))") // Output: "A"
print("Reversed '': \(reverseString(""))") // Output: ""
Output:
Reversed 'hello': olleh
Reversed 'Swift': tfiwS
Reversed 'A': A
Reversed '':
Program ended with exit code: 0
Xcode Screenshot