When developing applications with Swift, there might be cases where you need to reverse a given string. For example, reversing a string can help you check if it’s a palindrome (a string that reads the same forwards and backward) or decrypt a message that has been encoded in reverse.
This example-based article shows you a couple of different ways to reverse a string with the Swift programming language.
Using the string reversed() method
Example:
let str = "slingacademy.com"
let reversed = String(str.reversed())
print(reversed)
Output:
moc.ymedacagnils
The reversed() method is called on the str string and returns a ReversedCollection<Character> that represents the elements of the original string in reverse order. From this point, we use the String initializer to create a new string with the characters in reverse order.
Using a for loop
Example:
let str = "ABCDEFGH"
var reversedStr = ""
for char in str {
reversedStr = String(char) + reversedStr
}
print(reversedStr)
Output:
HGFEDCBA
In the code above, we use a for loop to iterate over each character in the str string. On each iteration, the char variable is set to the current character in the loop and is then concatenated with the current value of reversedStr, with the + operator.
This tutorial end here. Happy coding and have a nice day!