Start learning free

LESSON 15 OF 415 · VARIABLES

Type Conversion in Swift: String(), Int() and Double()

Lesson Read the full explanation

In Swift, every value has a type: Int, Double, String, and so on. Sometimes you need to convert a value from one type to another.

Common type conversion methods:

String(x)           // converts Int or Double → String
Int(s)!             // converts String → Int
Double(s)!          // converts String → Double
Int(x)              // converts Double → Int (drops decimal)

Here are some examples:

let score = 42
let scoreStr = String(score)    // "42"

let weight = 70.8
let weightInt = Int(weight)     // 70  (decimal dropped)

let count = "100"
let countInt = Int(count)!      // 100

Note that converting a Double to Int with Int() simply drops the decimal - it does not round.


Assignment
Follow the Coding Tutorial and convert each variable to a different type!


Hint
Use String(), Int() conversion, and Int(s)!.

STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · VARIABLES

    Type Conversion in Swift, explained

    Why conversion is explicit

    Swift never changes a value's type behind your back. An Int and a Double cannot be added, and a String cannot be joined to a number. When you need a different type, you create a new value of that type with an initialiser such as String(x), Int(x) or Double(x). The original is not touched.

    The common conversions

    GoalCodeResult
    number to textString(42)"42"
    Double to IntInt(70.8)70
    text to IntInt("100")Optional(100)
    text to DoubleDouble("9.5")Optional(9.5)
    Int to DoubleDouble(25)25.0

    Number to string

    String(score) builds the text form of a number, so String(42) is "42" and String(9.99) is "9.99". Use it before joining a number to text with +. Interpolation, "\(score)", does the same job inside a longer string.

    Double to Int truncates

    Int(price) with price = 9.99 gives 9. The decimal part is dropped, not rounded: the conversion truncates toward zero, so Int(3.99) is 3 and Int(-3.99) is -3.

    Int to Double

    Double(age) turns 25 into 25.0. You need it whenever an Int meets a Double in arithmetic: with age = 25 and price = 9.99, age * price does not compile, but Double(age) * price is 249.75. It also gives a fractional result for division, since Double(age) / 2 is 12.5 while age / 2 is 12.

    String to number can fail

    Not every string is a number. Int("2024") works, but Int("abc"), Int("9.5") and Int(" 5") have no valid result. Swift models this with an optional: Int(year) returns an Int?, which holds either the number or nil.

    print(Int("2024") as Any, Int("abc") as Any, Int("9.5") as Any)
    print(Double("9.5") as Any)
    
    Optional(2024) nil nil
    Optional(9.5)
    

    To get the plain number you must unwrap the optional. Three ways, from the lesson's quick one to the safest:

    • Int(year)! force-unwraps. It is correct only when you are certain the text is a number. On nil the program crashes.
    • Int(year) ?? 0 supplies a default when the conversion fails.
    • if let n = Int(text) { ... } runs a block only when the conversion succeeds.
    let bad = "abc"
    if let n = Int(bad) {
        print(n)
    } else {
        print("not a number")
    }
    print(Int("x") ?? 0)
    
    not a number
    0
    

    What the optional looks like

    If you store Int(year) without unwrapping, the constant has the type Int?. Printing it shows the wrapper, Optional(2024), and arithmetic is rejected:

    let year = "2024"
    let yearInteger = Int(year)
    print(yearInteger + 1)
    
    error: value of optional type 'Int?' must be unwrapped to a value of type 'Int'
    

    That error is the reason the lesson ends the line with !. With it, Int(year)! + 1 is 2025.

    The exercise, step by step

    The starter code gives three constants: age (an Int, 25), price (a Double, 9.99) and year (a String, "2024"). Below them, add three more.

    1. ageString: the text form of age, built with String(age). Its value is "25".
    2. priceInteger: the integer form of price, built with Int(price). Its value is 9, because the decimals are dropped.
    3. yearInteger: the integer form of year, built with Int(year)!. Parsing returns an optional, and the ! unwraps it. It is safe here because "2024" is a valid number. Its value is 2024.

    The solution in Swift

            let age = 25
            let price = 9.99
            let year = "2024"
    
            let ageString = String(age)
            let priceInteger = Int(price)
            let yearInteger = Int(year)!
    

    After these lines, ageString is a String, and priceInteger and yearInteger are Ints. The constants age, price and year keep their original types and values.

    More Swift details

    • Converting to Double for division. age / 2 is integer division, but Double(age) / 2 is 12.5.
    • Exact conversion. Int(exactly: 3.5) is nil, while Int(exactly: 3.0) is Optional(3).
    • Bases. Int("ff", radix: 16) parses hexadecimal and gives Optional(255).

    Common mistakes

    • Expecting rounding. Int(9.99) is 9, not 10.
    • Forgetting the ! or another unwrap. Without it, yearInteger would be an Int?, and arithmetic on it would not compile.
    • Force-unwrapping text you did not check. User input should go through if let or ??.
    • Mixing types in arithmetic. age * price does not compile. Write Double(age) * price, which is 249.75.

    Key takeaways

    • Conversions create new values with String(...), Int(...) and Double(...).
    • Int(someDouble) truncates toward zero.
    • Converting text to a number returns an optional; unwrap it with ! only when it cannot fail.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free