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 String to Int Example

Convert Strings to Ints and Ints to Strings. Handle invalid string data and optionals.
Convert. No transformation is quite like the butterfly's. Its bright wings emerge from the cocoon. Meanwhile (in Swift 4) we transform Strings and Ints.
With conversion methods, we can change from Strings to Ints and back again. This is often useful. For the most efficient representation of data, Ints are often ideal.
Int to String. Let us begin with an example that converts an Int (100) to a String ("100"). We use the String() init method. This method always returns a String.

Then: We compare the string returned against the string literal "100." They are equal, so we know our conversion succeeded.

Note: This String init does not return an optional. It always succeeds, as any Int can be represented in text.

Swift program that converts Int to String // This is an Int value. let number = 100 // Convert Int into String with String init. let numberString = String(number) // Display string. print(numberString) // The string's characters can be tested. if numberString == "100" { print(true) } Output 100 true
String to Int. This is the opposite conversion. We take a String and try to convert it into an Int. This conversion does not always work. We invoke the Int init and test the result.

If let: We use optional binding to extract the Int from the return value (an optional).

Info: If no Int exists, the inner statement is not reached. So we can determine when an Int() use fails because of an invalid format.

Swift program that converts String to Int // This is a String. let code = "100" // Use Int on the String. // ... This returns an Optional Int. // ... Use optional binding "if let" to get the number. if let numberFromCode = Int(code) { print(numberFromCode) } Output 100
Invalid strings. Some strings cannot be represented as an Int. For example the string XYZ corresponds to no Int. We use Int() as before, but handle errors in an else-clause.

Tip: The "if let" syntax offers advantages here. We can access the value if it exists, but also can branch on a parse that fails.

Swift program that uses Int with invalid String // This String has no numeric characters. let invalid = "XYZ" // Try to convert to an Int. if let parsedNumber = Int(invalid) { // This is not reached as the optional is Nil. print("?") } else { // This statement is printed. print("Not valid") } Output Not valid
Optionals. In Swift we often use optionals. Here we convert an optional String into a String. And then we convert the String back into an optional one.

Syntax: We use the exclamation mark to access the value in a non-nil optional. We use a question mark to specify an optional container.

Optionals
Swift program that uses converts optional to String // Create an optional String. var animal: String? = "fish" print(animal) // Convert optional to String. var animalValue = animal! print(animalValue) // Convert String to optional String. var animalOptional: String? = animalValue print(animalOptional) Output Optional("fish") fish Optional("fish")
Character, Int. In Swift we can convert an Int like 97 into its equivalent Unicode character. We must use the UnicodeScalar type. We can also get UInt values from a String.Character, UInt8, UnicodeScalar
String, byte array. With the utf8 property on a String, we get an array of UInt8 values. This is a byte array. We can manipulate those bytes (like integers).Convert String, Bytes
A review. Conversions in programs are complex and may fail. With optionals and optional binding, we handle these conversions with grace in Swift 3. This makes programs better.
© 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