C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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
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
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.
OptionalsSwift 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")