TheDeveloperBlog.com

Home | Contact Us

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

<< Back to SWIFT

Swift Convert Int to Character: UnicodeScalar, utf8

UnicodeScalar. In Swift a Character can be constructed from a UnicodeScalar value. And we can build up a UnicodeScalar from an Int. This allows many conversions.
With utf8 and utf16, both properties on a String, we can access all Int values of the characters of a String. With these properties, we can apply number-based conversions to characters.
Int to character. This example converts an Int that represents an ASCII char to an actual Character. The number 97 indicates a lowercase "a."

UnicodeScalar: We convert the value 97 to a UnicodeScalar instance with an init method. We then create a Character from that.

Result: We find that the value 97 was converted into a Character that indicates a lowercase letter "a."

Swift program that converts Int to Character let value = 97 // Convert Int to a UnicodeScalar. let u = UnicodeScalar(value) // Convert UnicodeScalar to a Character. let char = Character(u) // Write results. print(char) Output a
Get Ints from Characters. Here we apply the utf16 and utf8 properties on a String. These return Ints that represent that characters in a String.

Utf16: This returns UInt16 values. We can convert these to an Int or cast them with no errors.

Utf8: This returns UInt8 chars. It is important that the string not contain non-ASCII characters when we use this.

Swift program that converts string characters to Ints let value = "abc" for u in value.utf16 { // This value is a UInt16. print(u) } print("") // Write newline. for u in value.utf8 { // This value is a UInt8. print(u) } Output 97 98 99 97 98 99
ROT13. Some algorithms, like the ROT13 substitution cipher, require converting from characters to Ints. We can alter characters based on their numeric values.ROT13
A review. Every character has an underlying integer value. In Swift we can use this value, along with UnicodeScalar, to create a Character. This process is logical.
© 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