Reverse a String in Swift


In this tutorial, you are going to learn how to reverse a given string in Swift programming.

Swift provides us with a built-in method which is the reversed() method. It can help us to reverse a string. Below is the example:

var fruit = "Apple"
var fruitReversed = String(fruit.reversed())

print( fruitReversed )

Output

elppA

As you can see in the above program, we have a string with the value “Apple”. We have applied the reversed() method to our string and we can see that the string has been reversed. This is the most simple and easy way of reversing a string in Swift.

Alternative way (using for loop for reversing a Swift string)

We can also perform this task in an alternative way. In this example, we are going to use the Swift for loop.

Well, this one is going to be a little tricky. We are going to use the for loop in such a way that it can help us to perform our task. But this is not the easy one like you have seen in our first example. But it is still better to learn an alternative way to uplift your skill.

Below is the example:

var fruit = "Apple"
var fruitReversed = ""

// looping through each character
for char in fruit {
  fruitReversed = "\(char)" + fruitReversed
}

print(fruitReversed)

Output:

elppA

Well, in this example, we are using for loop to loop through each character. We first declared a variable with a blank string value "".

In the loop, we are putting each character of the string in a reversed way which resulting the final modification of the variable as a reversed string of our actual string.