Swift Type Conversion
Type conversion makes a value of one type from a value of another type.
Making a whole number from a decimal
This code changes a decimal value into a whole number value. That change is a conversion in action, and the print shows 3.
var price = 3.9
print(Int(price))Making a decimal from a whole number
The whole number 7 becomes a decimal number in the output. The second line names the new kind as Double.
var whole = 7
print(Double(whole))
print(type(of: Double(whole)))Making text from a number
The text value and the number print side by side on the first line. The second line names their kinds as String and Int, so the two 42 values differ in kind.
var number = 42
var label = String(number)
print(label, number)
print(type(of: label), type(of: number))Adding two number types fails
The first name holds a whole number and the second holds a decimal number. The compiler stops the sum with an error.
var a = 7
var b = 2.5
print(a + b)Example
var score = 9
var exact = Double(score)
var label = String(score)
print(exact)
print(label, score)
print(type(of: label))Key points
- Use Int() to make a whole number from a decimal number.
- Int() drops the decimal part rather than rounding it.
- Use Double() to make a decimal number from a whole number.
- Use String() to make text from a number.
- A whole number and a decimal number cannot be added in one sum.
In this example, score starts as the whole number 9. The Double line makes exact a decimal copy of score. The String line makes label a text copy of score. The first print shows 9.0. The second print shows the text and the number side by side as 9 9. The last print names the kind of label as String. String-to-number parsing comes later in this course, because it can fail.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
What value does Int(3.9) give?