Home
Map
String ReverseUse an extension to reverse the characters in a String. Create a Character array.
Swift
This page was last reviewed on Aug 22, 2023.
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.
extension
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 Length
Start We loop over the string with a while-loop. This is needed because we must avoid calling predecessor() on startIndex.
for
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 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.
This page was last updated on Aug 22, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.