Swift String reversed() Function



String reversed() Function

A reversed() function is used to reverse the order of the given string. It reverses the string without allocating new spaces. This function returns the ReversedCollection instance which contains an underlaying collection and provides access to its each element in reverse order. If you want to reverse a collection of the same type, then you have to use that collection-based initializer.

Syntax

Following is the syntax of the reversed() function −

func reversed() −> ReversedCollection<Self>

Parameter

This method does not take any parameters.

Return Value

The method returns the reversed collection.

Example 1

Swift program to reverse a string.

import Foundation

// Declaring a string
var str = "TutorialsPoint is a great learning platform"
print("Original String:", str)

// Reversing the order of the string
// Using reversed() method
let revStr = String(str.reversed())

print("Modified String:", revStr)

Output

Original String: TutorialsPoint is a great learning platform
Modified String: mroftalp gninrael taerg a si tnioPslairotuT

Example 2

Swift program to reverse input string −

import Foundation

// Declaring a string
var str = "TutorialsPoint"

// Reversing the order of the given string
// Using reversed() method
print("Reversed String:")
for s in str.reversed(){
   print(s)
}

Output

Reversed String:
t
n
i
o
P
s
l
a
i
r
o
t
u
T
swift_strings.htm
Advertisements