by @CodingExample

How to reverse a string in Swift

Home » swift » How to reverse a string in Swift

In Swift, we have a built-in `reversed() method by using that we can reverse a string.

let str = "how are you"

let reversedString = String(str.reversed())

print(reversedString)

Output:

uoy era woh

Reversing string using for loop

Similarly, we can also reverse a string using the for loop.

let str = "how are you"

var reversedString = ""

// looping through each character
for char in str {
  reversedString = "\(char)" + reversedString
}

print(reversedString)

Output:

uoy era woh