Start learning free

LESSON 15 OF 349 · VARIABLES

Type Conversion in Swift in Swift

Lesson

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()!.

STEP 1 OF 3
    Ctrl + Enter to check

    Type Conversion in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free