TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to SWIFT

Swift Reverse String

Use 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.Extension
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.startIndex, endIndex

While: We loop over the string with a while-loop. This is needed because we must avoid calling predecessor() on startIndex.

While

If: This logic ensures we do not call predecessor on startIndex. We terminate the loop once startIndex has been reached.

Append: We append characters to the Character array with append. We finally return a string based on these new characters.

Swift program that uses reverse extension method 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) Output 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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf