by Sai gowtham

How to reverse a string in Swift

In Swift, we have a built-in `reversed() method by using that we can reverse a string.

let str = "how are you"

let reversedString = String(str.reversed())

print(reversedString)

Output:

uoy era woh

Reversing string using for loop

Similarly, we can also reverse a string using the for loop.

let str = "how are you"

var reversedString = ""

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

print(reversedString)

Output:

uoy era woh

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course