Swift Tutorial Swift References

Swift - assignment operators example



The example below shows the usage of assignment and compound assignment operators:

  • = Assignment operator
  • += Addition AND assignment operator
  • -= Subtraction AND assignment operator
  • *= Multiply AND assignment operator
  • /= Division AND assignment operator
  • %= Modulo AND assignment operator
var a = 25.0
var b = 25

print("a = \(a) b = \(b) \n")

//Addition AND assignment operator
a += 5
print("a += 5 makes a = \(a)")

//Subtraction AND assignment operator
a -= 8
print("a -= 8 makes a = \(a)")

//Multiply AND assignment operator
a *= 4
print("a *= 4 makes a = \(a)")

//Division AND assignment operator
a /= 2
print("a /= 2 makes a = \(a)")

//Modulo AND assignment operator
//works only with integral operands
b %= 7
print("b %= 7 makes b = \(b)")

The output of the above code will be:

a =  25.0 , b =  25 

a += 5 makes a =  30.0
a -= 8 makes a =  22.0
a *= 4 makes a =  88.0
a /= 2 makes a =  44.0
b %= 7 makes b =  4

❮ Swift - Operators