Swift makes you clearly say when you want to change a value from one type to another. This helps avoid mistakes and keeps your code safe.
Type conversion is always explicit in Swift
let newValue = TypeName(oldValue)You write the target type name and put the value you want to convert inside parentheses.
If the conversion is not possible, Swift will give an error or you can use optional conversion.
let intVal = 5 let doubleVal = Double(intVal)
let str = "123" if let number = Int(str) { print(number) }
let pi = 3.14 let intPi = Int(pi)
This program converts a string to an integer explicitly. If the conversion works, it adds 1 and prints the result. If not, it shows an error message.
let ageString = "30" if let age = Int(ageString) { let nextYearAge = age + 1 print("Next year you will be \(nextYearAge) years old.") } else { print("Invalid age input.") }
Swift does not automatically convert types for you. You must always convert explicitly.
Use optional conversion (like Int(string)) when the conversion might fail.
Explicit conversion helps catch errors early and makes your code clearer.
Swift requires you to convert types explicitly to avoid mistakes.
Use the target type name with parentheses to convert values.
Optional conversions help safely handle cases where conversion might fail.