We have seen how to output the text, let’s now focus on numbers…
To recall (Swift: Types of variables – constants), we have seen that numbers can be declared either as integers, doubles or floats.
In Swift, as in any programming language, we can addition, subtract, multiply or divide numbers.
So let’s declare 2 variables as numbers and do some math…
var num1 : Int = 20
var num2 : Int = 4
var num3 : Double = 4.5
/* pay attention that you will either need to write a comma(,) or a point (.) – depending on your language setups */
Now, let’s take a look at the 5 basic arithmetic operations that you can perform in swift:
print(num1 + num2) // output is 24
print(num1 – num2) // output is 16
print(num1 * num2) // output is 80
print(num1 / num2) //output is 5
Print(num1 / num2) // output is 0
The logic behind remainder is the following: the program first computes how many times 4s will fit in the 20 (so here it is 5) and then it will give us the number which is left, that cannot be divided by 4 in order to give a whole number.
A last important remark, before moving forward is that we can use all these arithmetic operators only with variables that are of the same type. Indeed, if we try to multiply a whole number (for example the variable num1) with a double number (num3), we will incur an error
So to overcome this, we will need to declare the variable “num1” as a double also int the print function and this will resolve the issue
print(Double(num1) * num3) // output is 90