Home
Swift
Convert String to Int Example
This page was last reviewed on Aug 22, 2023.
Dot Net Perls
Convert. In Swift 5.8, we transform Strings and Ints. With conversion methods, we can change from Strings to Ints and back again. This is often useful.
For simple conversions, built-in methods are available in the Swift language. For more complex things, we may need to develop custom functions.
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.
// 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) }
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.
Tip 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.
// 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) }
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.
// 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") }
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.
Tip We use the exclamation mark to access the value in a non-nil optional. We use a question mark to specify an optional container.
Optional
// 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)
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.
Convert Int, Character
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
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.
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.