Swift String reversed()

The reversed() method reverses the given string.

Example

var msg = "Learn Swift"

// reverse msg var result = String(msg.reversed())
print(result) // Output: tfiwS nraeL

reversed() Syntax

The syntax of the string reversed() method is:

String(string.reversed()

Here, string is an object of the String class.


reversed() Parameters

The reversed() method doesn't take any parameters.


reversed() Return Value

  • returns the reversed string.

Example: Swift string reversed()

var text = "Reverse Day "

// reverse text var result = String(text.reversed())
print(result) var numbers = "123"
// reverse numbers var result1 = String(numbers.reversed())
print(result1)

Output

yaD esreveR
321

Using for Loop To Reverse String

In Swift, we can also use the for loop to reverse the given string. For example,

var text = "Reverse Day"
var result = ""

// loop through each character
for character in text {
 result = "\(character)" + result
}

print(result)

Output

yaD esreveR
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges