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
.
string
returned against the string
literal "100." They are equal, so we know our conversion succeeded.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.
Int
from the return value (an optional).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
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.
// 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
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.
nil
optional. We use a question mark to specify an optional container.// 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")
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
.
String
, byte
arrayWith 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).
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.