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
.
string
with a while
-loop. This is needed because we must avoid calling predecessor()
on startIndex
.startIndex
. We terminate the loop once startIndex
has been reached.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
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.