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

}

Reverse a String in Swift Programming language
This code snippet demonstrates the following.

  • How to assign a value to variable.
  • How to create an Array of Characters and assign empty value.(Character)
  • Iterate over the string using for-in loop.
  • How to add new elements to an Array.
  • How to create empty String variable.
  • Use the standard for loop to traverse through an array.
  • Concatenate Strings and character
  • Using for .. in

In Category: Programming, Xcode

Ravi Shankar

A polyglot software developer and now exploring Swift and iOS development. If you would like to learn from me then check out services page.

Show 5 Comments
  • andreas August 6, 2014, 6:37 pm

    or short:

    var str = “Hello, playground”

    var reverseStr = “”

    for character in str {
    reverseStr = character + reverseStr
    }

    • rshankar August 7, 2014, 1:48 am

      Thanks for the suggestion.

  • Pedro August 26, 2014, 2:57 am

    for char in identityNumber{
    reversedString = char + reversedString

    }
    ‘String’ is not convertible to ‘Character’

    • rshankar August 26, 2014, 3:20 am

      Looks like some changes have been introduced in Xcode 6 beta 6. Here is the fix.

      var str = “Hello, playground”

      var reverseStr = “”

      for character in str {
      reverseStr = String(character) + reverseStr
      }

  • doches October 31, 2014, 8:14 pm

    Even simpler, using the builtin collections functions:

    var str = “abcdef”
    var revStr = String(reverse(str))

Leave a Comment