Reverse StringUse an extension to reverse the characters in a String. Create a Character array.
Reverse string. A string contains characters. In Swift, no reverse() func is available to reverse the ordering of these characters. But an extension can be built.
Logic. 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.
Detail We loop over the string with a while-loop. This is needed because we must avoid calling predecessor() on startIndex.
Detail This logic ensures we do not call predecessor on startIndex. We terminate the loop once startIndex has been reached.
Detail 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 = i.predecessor() } // 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.
A review. 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2023 Sam Allen.