Swift Type Casting

Swift Type Casting

Type casting allows you to convert a value from one data type to another.

Because Swift is a strictly typed language, it does not implicitly convert values for you.

If you want to add an Int and a Double, you must manually cast one to match the other.


Converting Numbers

You can convert numeric types by passing the value you want to cast into the initializer of the new type.

For example, you can wrap an integer in Double() to convert it to a floating-point number.

Numeric Conversion:

let intValue: Int = 10
let doubleValue: Double = 5.5

// We must convert intValue to a Double before adding let result = Double(intValue) + doubleValue print("The result is (result)")


Converting Numbers to Strings

You frequently need to convert numbers into strings, especially when displaying UI elements.

You can do this using the String() initializer.

Number to String:

let score = 100
let message = "Your final score is " + String(score)
print(message)

Note: String interpolation \(score) achieves the same result and is often preferred for readability.


Converting Strings to Numbers

Converting a String to an Int is slightly different, because the string might not contain a valid number.

For instance, you cannot convert "Hello" to an integer.

When you use Int(), it returns an Optional, which we will cover later. But essentially, it returns the number if successful, or nil if it fails.

String to Number:

let numericString = "42"
if let convertedNumber = Int(numericString) {
    print("Successfully converted to \(convertedNumber)")
} else {
    print("Conversion failed.")
}

Exercise

How do you explicitly cast the integer variable `x` to a Double?