Sling Academy
Home/Swift/2 Ways to Reverse a String in Swift

2 Ways to Reverse a String in Swift

Last updated: February 23, 2023

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!

Next Article: Swift: Remove Leading and Trailing Whitespace of a String

Previous Article: 3 Ways to Generate Random Strings in Swift

Series: Working with Strings in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)