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?