Type Conversion
Part of the Fundamentals section of Coddy's Swift journey — lesson 34 of 86.
Since readLine() returns a String?, you'll often need to convert that string into a number to perform calculations. Swift requires explicit type conversion — it won't automatically turn a string into an integer or double.
To convert a string to an integer, use the Int() initializer. Because the conversion might fail (the string could contain letters instead of digits), it returns an optional:
let input = "42"
if let number = Int(input) {
print(number + 10) // Output: 52
}For decimal numbers, use Double():
let priceString = "19.99"
if let price = Double(priceString) {
print(price * 2) // Output: 39.98
}This is especially useful when combining readLine() with numeric operations. You can chain the unwrapping together:
if let input = readLine(), let age = Int(input) {
print("Next year you'll be \(age + 1)")
}The comma in the if let statement means both conditions must succeed — the input must exist, and it must be convertible to an integer.
Challenge
EasyRead two inputs: a decimal number as a string and an integer as a string. Convert them to their appropriate numeric types and calculate their product.
You will receive the following inputs:
- First line: A decimal number (e.g.,
"3.5") - Second line: An integer (e.g.,
"4")
Use readLine() to read both inputs. Convert the first input to a Double and the second to an Int. Then multiply them together and print the result.
Use if let with chained optional binding to safely unwrap both the input and the converted value.
Print: The product of the two numbers as a Double
Cheat sheet
Swift requires explicit type conversion between strings and numbers.
To convert a string to an integer, use Int(). It returns an optional because conversion might fail:
let input = "42"
if let number = Int(input) {
print(number + 10) // Output: 52
}To convert a string to a decimal number, use Double():
let priceString = "19.99"
if let price = Double(priceString) {
print(price * 2) // Output: 39.98
}You can chain optional unwrapping with readLine() using a comma in if let. Both conditions must succeed:
if let input = readLine(), let age = Int(input) {
print("Next year you'll be \(age + 1)")
}Try it yourself
// Read the decimal number as a string
if let decimalString = readLine() {
// Read the integer as a string
if let intString = readLine() {
// TODO: Write your code below
// Convert decimalString to Double and intString to Int using if let
// Then calculate and print their product
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input