Skip to content

Reversing a String with reversed(Swift)

Swift, String Manipulation1 min read

When working with strings in Swift, there are various ways to manipulate and transform them. One common task is to reverse a given string. In Swift, you can achieve this easily using the reversed() method. In this article, we'll explore how to reverse a string in Swift using reversed() and walk through some practical examples to solidify your understanding.

Using reversed() to Reverse a String

In Swift, the reversed() method is available on types that conform to the BidirectionalCollection protocol, which includes String. The reversed() method returns a ReversedCollection of the same type as the original collection.

Let's take a look at the basic usage of reversed() to reverse a string:

1let originalString = "Hello, World!"
2let reversedString = String(originalString.reversed())
3print(reversedString) // Output: "!dlroW ,olleH"

As shown in the example above, we call the reversed() method on the original string and then convert the result into a new String. This effectively reverses the characters within the string.

Handling Unicode Characters

It's important to note that when reversing a string containing extended grapheme clusters (a single human-readable character made up of multiple Unicode scalars), the reversed() method respects the integrity of those clusters. This ensures that the meaning of each character is preserved even when the string is reversed.

Consider the following example:

1let cafe = "Café"
2let reversedCafe = String(cafe.reversed())
3print(reversedCafe) // Output: "éfaC"

In this case, the accented 'é' remains properly positioned after the string reversal.

Reversing Words in a Sentence

You can also reverse the words within a sentence using reversed(). To achieve this, you can split the original string into an array of words, reverse the order of the elements in the array, and then join them back together into a single string.

1let sentence = "Swift is amazing"
2let reversedSentence = sentence.components(separatedBy: " ").reversed().joined(separator: " ")
3print(reversedSentence) // Output: "amazing is Swift"

In the example above, we first split the sentence into an array of words using components(separatedBy:), then reversed() the array, and finally joined the elements back together using joined(separator:).

Handling Empty Strings

When dealing with empty strings, it's essential to consider how the reversed() method behaves. Let's see how it handles an empty string:

1let emptyString = ""
2let reversedEmptyString = String(emptyString.reversed())
3print(reversedEmptyString.isEmpty) // Output: true

As demonstrated in the example, when reversing an empty string, the result is still an empty string.