Swift
What is Compound Assignment Operator in Swift?
8 ay önce yazıldı. | Okuma süresi: 2 dk.

In Swift, a compound assignment operator is a shorthand way of combining an arithmetic operation with assignment. It allows you to modify the value of a variable or property by performing an operation (e.g., addition, subtraction, multiplication, division) on it and assigning the result back to the same variable or property in a single step.

Compound assignment operators are concise and can make your code more readable. (Really, How?)

"+=" (Addition and Assignment): This operator adds the right-hand operand to the left-hand operand and assigns the result back to the left-hand operand.


var x = 7
x += 3 // Equivalent to: x = x + 3
// Now, x is 10


"-=" (Subtraction and Assignment): This operator subtracts the right-hand operand from the left-hand operand and assigns the result back to the left-hand operand.


var y = 12
y -= 4 // Equivalent to: y = y - 4
// Now, y is 8


Yeah more: "*=" , "/=" (multiply and divide using same mechanism)

These compound assignment operators are convenient when you want to perform a common operation and update a variable's value in a concise manner, especially within loops or when you need to repeatedly modify a variable.


Page generated in 0.0172 seconds.