3.1. Arithmetic Operations
Let's do some arithmetic operations using Swift now. For addition, subtraction, multiplication, and division, we use +,-,*, and / respectively. Let's look at the following code:
let num1 = 5
let num2 = 33
//Addition...
let sum = num1 + num2
//Subtraction...
let difference = num2 - num1
//Multiplication...
let product = num1 * num2
//Division (and remainder)...
let divided = num2 / num1
let remainder = num2 % num1
print(
"""
Results:
Sum = \(sum)
Difference = \(difference)
Product = \(product)
Division result = \(divided)
Division remainder = \(remainder)
"""
)It prints:
From the above example, it feels very intuitive how you can directly use the operators +, -, *, and / do the arithmetic operations. The remainder of a divide operation can be done with the dedicated operator %.
However, there are a few caveats to these operations. Let's look into the following code:
What do you think will happen?
It should show something like the following:

Remember, Double is a 64-bits long number and Int is a 32-bits long number? We are trying to add an Int(myInt) and a Double(myDouble) together and put the result into an Int(sum). First of all, if you add an Int and a Double together, it results in a Double value, since Double has the largest capacity of the two. Now, we are trying to put that Double value into the constant sum, which is and Int. An Int doesn't have the capacity to hold a Double. So, it is yelling at us 🤦♂️
You should always be careful of the types of data before you use arithmetic operators in Swift. More on this later.
Last updated
Was this helpful?