0
0
Swiftprogramming~5 mins

Type conversion is always explicit in Swift

Choose your learning style9 modes available
Introduction

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.

When you want to add an integer and a floating-point number.
When you need to convert a string to a number before doing math.
When you want to store a smaller number type into a bigger number type.
When you want to convert between different types like Int and Double explicitly.
When you want to avoid unexpected errors by making conversions clear.
Syntax
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.

Examples
Convert an integer to a double explicitly.
Swift
let intVal = 5
let doubleVal = Double(intVal)
Try to convert a string to an integer safely using optional binding.
Swift
let str = "123"
if let number = Int(str) {
    print(number)
}
Convert a double to an integer by dropping the decimal part.
Swift
let pi = 3.14
let intPi = Int(pi)
Sample Program

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.

Swift
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.")
}
OutputSuccess
Important Notes

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.

Summary

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.