Swift – Reverse a String

To reverse a String in Swift, call reversed() function on this String. reversed() returns ReversedCollection. To convert this to String, use String().

The syntax to reverse a String str using reversed() is

</>
Copy
var result = String(str.reversed())

Example

In this example, we will take a string in variables str and reverse it using String.reversed().

main.swift

</>
Copy
var str = "Hello World"
var result = String(str.reversed())
print("Original String : \(str)")
print("Reversed String : \(result)")

Output

Original String : Hello World
Reversed String : dlroW olleH

Conclusion

In this Swift Tutorial, we learned how to reverse a string using String.reversed() function.