Site icon Ravi Shankar

Reverse a String in Swift

Here is a simple code snippet written in Swift programming language for reversing a string.

import Cocoa


//Assigning a value to a String variable

var str = "Hello, playground"


//Create empty character Array.

var strArray:Character[] = Character[]()


//Loop through each character in the String

for character in str {

//Insert the character in the Array variable.

strArray.append(character)

}


//Create a empty string

var reversedStr:String = ""


//Read the array from backwards to get the characters

for var index = strArray.count - 1; index >= 0;--index {

//Concatenate character to String.

reversedStr += strArray[index]

}


reversedStr


the shorter version to reverse is (thanks Andreas)


var str = “Hello, playground”

var reverseStr = “”

for character in str {

reverseStr = character + reverseStr

}


This code snippet demonstrates the following.

Exit mobile version