Let’s discuss about compound assignment operators in Swift!
Our variable’s values may need to be adjusted on occasion. We know that arithmetic operators can be used to update our variables like this:
var points = 72; points = points + 1; print(points); // Output: 73
We also have the option of using compound assignment operators. It’s a shorthand method for modifying the value of variables.
If we wanted to use a compound assignment operator (
+=) to update our prior code, we’d use the following syntax:
var points = 72; points += 1; print(points); // Output: 73
We don’t need to reference
points twice now that we’ve used a compound assignment operator!
Here are some of the basic compound assignment operators:
+=add and assign the sum.
-=subtract and assign the difference.
*=multiply and assign the product.
/=divide and assign the quotient.
%=divide and assign the remainder.
Check out how these operators work as we use compound assignment operators to change the value of a
pounds five times:
var pounds = 6; pounds += 4; // same as pounds = 6 + 4 print(pounds); // Prints: 10 pounds -= 3; // same as pounds = 10 - 3 print(pounds); // Prints: 7 pounds *= 5; // same as pounds = 7 * 5 print(pounds); // Prints: 35 pounds /= 6; // same as pounds = 35 / 6 print(pounds); // Prints: 5 pounds %= 2; // same as pounds = 5 % 2 print(pounds); // Prints: 1
pounds started off with a value of
6, but it changed every time we used a compound assignment operator, and towards the end of the programme, it had a value of
Be careful to include a space before and after the assignment operator
= when using compound assignment operators otherwise, we’ll get an error.
Here are some useful tools to help you along your journey!
Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.