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
//
to add lines of comments to your code. This will help to understand better your code.
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
Be the first to comment