Reverse string. A string contains characters. In Swift 5.8, no reverse() func is available to reverse the ordering of these characters. But an extension can be built.
To reverse a string, we must create a new buffer (an array of characters). Then, we loop in reverse over the existing string, adding characters to the new character buffer.
Func. Here we use the extension keyword to add a reverse() method to the String type. The logic has some tricks to it. We use the endIndex and startIndex properties on the "self" String.
Info This logic ensures we do not call predecessor on startIndex. We terminate the loop once startIndex has been reached.
Finally We append characters to the Character array with append. We finally return a string based on these new characters.
extension String {
func reverse() -> String {
let data = self
var array = [Character]()
// Begin at endIndex.
var i = data.endIndex
// Loop over all string characters.
while (i != data.startIndex) {
// Get previous index if not on first.
if i > data.startIndex {
i = data.index(i, offsetBy: -1)
}
// Add character to array.
array.append(data[i])
}
// Return reversed string.
return String(array)
}
}
// Test string reversal extension method.
var animal = "bird"
let result = animal.reverse()
print(result)
var plant = "carrot"
let result2 = plant.reverse()
print(result2)drib
torrac
Some notes. The reverse() method above is not marked as "mutating," so it cannot change the self String instance. Instead it returns a new String.
With extension method syntax, we can add useful (even if not common) funcs to types like String. To reverse the characters in a String, we use a simple looping algorithm.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 22, 2023 (edit).