Swift program to reverse a string using library function

SwiftServer Side ProgrammingProgramming

This tutorial will discuss how to write swift program to reverse a string using library function.

A string is an ordered set of characters, for example, "TutorialsPoint" It is used to represent textual data. Swift support a String data type which is used to create a string type variable, or we can say to represent strings.


  • Following is the syntax to create string −

var mystr : String = “My String” 
var mystr = “ My string”

Reversing of a string means reverse the order of the characters present in the specified string. Swift provide a built in method named reversed(). This function is used reverse the order of the given string. This function returns a ReversedCollection, so to convert it into string we use String() function.

  • Following is the syntax- −

var outputStr = String(str.reversed())

Below is a demonstration of the same −


Suppose our given input is −

String = Car is blue


The desired output would be −

Reversed string = eulb si raC


Following is the algorithm −

  • Step 1− Declare a variable of String type. Here the value of this variable can be pre-defined or user defined.

  • Step 2− Reverse the string using reversed() function.

var output String(myStr.reversed())
  • Step 3− Print the output.


The following program shows how to reverse a string using library function.

import Foundation import Glibc var myStr : String = "TutorialsPoint" print("Original string:", myStr) // Reversed a string // Using reversed() function var output = String(myStr.reversed()) print("Reversed String:", output)


Original string: TutorialsPoint 
Reversed String: tnioPslairotuT

Here in the above code, we have a string = "TutorialsPoint" Now using myStr.reversed() we reversed the given string that is  - tnioPslairotuT

Updated on 10-Oct-2022 12:47:50