Lesson 10Swift Basics
Type Conversion
Type Conversion
Sometimes you need to convert values from one type to another. Swift requires explicit conversion for safety!
Common Conversions
Int → Double
Double(intValue)Double → Int
Int(doubleValue)Truncates decimals!
String → Int
Int(stringValue)Returns Optional!
Int → String
String(intValue)Important Notes
Int(3.9)gives 3, not 4 (truncates)Int("hello")returns nil (can't convert)- String to number conversions return Optionals
Safe String Conversion
Use if let to safely convert strings:
if let num = Int("42") { print(num) }main.swift
// Int to Double
let age: Int = 12
let ageDouble = Double(age)
print(ageDouble) // 12.0
// Double to Int (truncates decimal part)
let price = 9.99
let priceInt = Int(price)
print(priceInt) // 9
let rounded = Int(3.7)
print(rounded) // 3 (not 4!)
// Mixing types requires conversion
let a: Int = 5
let b: Double = 3.14
let result = Double(a) + b
print(result) // 8.14
// String to Int (returns Optional!)
let numberString = "42"
if let number = Int(numberString) {
print("Converted: \(number)")
} else {
print("Conversion failed")
}
// Invalid conversion returns nil
let invalid = Int("hello")
print(invalid) // nil
// Int to String
let score = 100
let scoreString = String(score)
print("Score: " + scoreString)
// String to Double
let piString = "3.14159"
if let pi = Double(piString) {
print("Pi is \(pi)")
}
// Bool to String
let isTrue = true
print(String(isTrue)) // "true"
// Calculate birth year
let currentYear = 2024
let userAge = 12
let birthYear = currentYear - userAge
print("Born in \(birthYear)")Try It Yourself!
Convert a user's age from a String to an Int, then calculate and print their birth year!
Module Complete!
Congratulations! You've completed the Swift Basics module. Next up: Control Flow!