Welcome back to CodeYourCraft! Today, we're going to dive into the world of Swift Assignment Operators. These operators are essential tools in our Swift programming arsenal, helping us assign and modify values with ease. 🎯
Assignment operators are special symbols used in Swift to assign values to variables and constants, and to update the values of variables. They are a convenient way to perform an operation and store its result in a variable, all in one line of code.
The most fundamental assignment operator is the equal sign (=). It assigns the value on its right side to the variable or constant on its left side.
var myNumber: Int = 0
myNumber = 10 // myNumber now equals 10Swift provides several shorthand assignment operators to make our code cleaner and more readable. Here are some examples:
The addition assignment operator (+=) adds a value to the existing value of a variable and then assigns the result back to the variable.
var myNumber: Int = 0
myNumber += 10 // myNumber now equals 10 (originally 0, then 10 added)The subtraction assignment operator (-=) subtracts a value from the existing value of a variable and then assigns the result back to the variable.
var myNumber: Int = 10
myNumber -= 5 // myNumber now equals 5 (originally 10, then 5 subtracted)The multiplication assignment operator (*=) multiplies a value by the existing value of a variable and then assigns the result back to the variable.
var myNumber: Int = 2
myNumber *= 3 // myNumber now equals 6 (originally 2, then 2 multiplied by 3)The division assignment operator (/=) divides a variable's value by another value and then assigns the result back to the variable.
var myNumber: Int = 12
myNumber /= 2 // myNumber now equals 6 (originally 12, then divided by 2)The modulus assignment operator (%=) calculates the remainder of a division operation and assigns the result back to the variable.
var myNumber: Int = 10
myNumber %= 3 // myNumber now equals 1 (originally 10, then modulus 3)What does the addition assignment operator do?
That's it for today! Practice using these assignment operators in your Swift projects to make your code more efficient and readable. See you in the next lesson! 🎯