Math operators
Addition, subtraction, multiplication and division of variables.
Math operators
Addition, subtraction, multiplication and division of variables.
0
0
Checkbox to mark video as read
Mark as read

You can do math operations just using math characters.

2 + 1

When the system find an operation on our code, this will be replaced with the result. That means that we can use them anywhere.

@State var money: Int = 1000 + 2000 
// This is exactly the same as
@State var money: Int = 3000

We can use math operations between variables as well.

@State var bankMoney: Int = 1000
@State var cash: Int = 100
@State var totalMoney: Int = bankMoney + cash

In addition to adding, we can subtract, multiply and divide:

3 - 1 // Substract
3 * 2 // Multiply
6 / 3 // Divide

Math operations are not just limited to 2 elements, you can create complex operations. This follows "math rules", meaning that multiplications and divisions will be solved first, and then additions and subtractions. However you can use parenthesis if you want to solve change that order or just to make it more readable.

@State var numberOfCars: Int = 100
@State var numberOfBikes: Int = 50

@State var numberOfWheels = (numberOfCars * 4) + (numberOfBikes * 2) // Same result but more readable
@State var numberOfKeys = (numberOfCars + numberOfBikes) * 2 // Two keys per vehicle

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy