Swift Type Conversion

Swift never changes the type of a value behind your back. An Int stays an Int, and a Double stays a Double until you ask for a change. This strict habit prevents bugs where a price loses its decimal part or a number turns into text without warning.

Picture two glasses of different shapes. Water poured from a tall glass into a wide glass keeps its volume, yet you must pour it yourself. Type conversion works the same way: you create a new value of the target type from the original value.

Diagram: Conversion Map

            Double(x)
   Int  ------------------>  Double
   Int  <------------------  Double
            Int(x)  (drops decimals)

            String(x)
 Number ------------------>  String
 Number <------------------  String
         Int("42") / Double("3.5")
         (result is an optional)

Converting Between Numbers

Swift refuses to add an Int to a Double directly. Wrap one value in the initializer of the other type.

let itemCount = 4
let price = 2.5
let total = Double(itemCount) * price
print(total)   // Output: 10.0

The expression Double(itemCount) builds a new Double from the integer and leaves itemCount untouched.

Truncation When Converting to Int

Converting a Double to an Int cuts off the decimal part. Swift does not round the number.

let temperature = 36.9
let whole = Int(temperature)
print(whole)   // Output: 36

Use the rounded() method before the conversion when you need the nearest whole number.

let nearest = Int(temperature.rounded())
print(nearest) // Output: 37

Converting Numbers to Strings

The String initializer turns any number into text. String interpolation reaches the same result inside a longer message.

let score = 85
let text = String(score)
print("Score: " + text)   // Output: Score: 85
print("Score: \(score)")  // Output: Score: 85

Converting Strings to Numbers

Text cannot always become a number. The string "42" converts well, while "forty" fails. Swift handles this risk by returning an optional value. The result holds a number on success and nil on failure.

let good = Int("42")
let bad = Int("forty")
print(good)  // Output: Optional(42)
print(bad)   // Output: nil

if let age = Int("29") {
    print("Age is \(age)")   // Output: Age is 29
}

Optional binding with if let unwraps the value safely. A later topic covers optionals in depth.

Example: Tip Calculator

Real programs read numbers as text from text fields. The example below turns that text into numbers, calculates a tip, and builds a message.

let billText = "48.50"
let tipPercent = 15

if let bill = Double(billText) {
    let tip = bill * Double(tipPercent) / 100
    print("Tip: \(tip)")   // Output: Tip: 7.275
}

Literals Adapt Automatically

A plain number written in code has no fixed type until Swift reads the context. The line let sum = 3 + 0.5 works because both literals become Double. The restriction applies only to values stored in constants or variables.

let whole = 3
// let broken = whole + 0.5        // Error
let fixed = Double(whole) + 0.5    // 3.5

Converting Other Types

Many types offer initializers that accept values of another type. A Bool becomes text with String(true). A Character becomes a string with String("A"). An array of characters joins into one string with String(characters).

Common Mistakes

Adding an Int to a Double without conversion triggers a type mismatch error. Convert one side to make both match. Choosing the more precise type, usually Double, avoids losing decimal places.

Force unwrapping the result of Int("abc") crashes the program. Use if let or the nil-coalescing operator, as in Int(text) ?? 0.

Real-World Use

Text fields in forms always deliver text. Calculators, budget trackers, and unit converters turn that text into numbers, run the math, and convert the result back to text for display. Safe conversion decides whether the app reports a clear error or crashes on unusual input.

Key Takeaways

  • Swift converts types only when you request it.
  • Use Double(x) and Int(x) to move between number types.
  • Converting a decimal number to an integer drops the decimal part.
  • Converting text to a number returns an optional that you unwrap.