Assignment Operators in Swift

Assignment Operators are used to assign value to a variable. They can perform basic mathematical arithmetic operators like addition, subtraction, multiplication, etc., and then assign the result back to the left operand variable.

The following table lists out all the arithmetic operators in Swift.

Operator
Symbol
NameExampleDescription
=Assignmentx = 2Assigns the value of 2 to x.
+=Addition Assignmentx += 2Adds the value of 2 to that of x, and assigns the result to x.
-=Subtraction Assignmentx -= 2Subtracts the value of 2 from that of x, and assigns the result to x.
*=Multiplication Assignmentx *= 2Multiplies the value of 2 to that of x, and assigns the result to x.
/=Division Assignmentx /= 2Finds the quotient in the division of x by 2, and assigns the quotient to x.
%=Modulus Assignmentx %= 2Finds the remainder in the division of x by 2, and assigns the remainder to x.
Python Arithmetic Operators

Assignment Operators

1. Assignment

Assignment operator takes two operands: x and y, and assigns the right operand y to left operand x.

main.swift

var x: Int
x = 5
print("x is \(x)")

Output

x is 5

2. Addition Assignment

Addition assignment operator takes two operands as inputs: x and y, and assigns the sum of x and y to x.

main.swift

var x = 5
var y = 2
x += y
print("x is \(x)")

Output

x is 7

3. Subtraction Assignment

Subtraction assignment operator takes two operands as inputs: x and y, and assigns the difference x – y to x.

main.swift

var x = 5
var y = 2
x -= y
print("x is \(x)")

Output

x is 3

4. Multiplication Assignment

Multiplication assignment operator takes two operands as inputs: x and y, and assigns the product of x and y to x.

main.swift

var x = 5
var y = 2
x *= y
print("x is \(x)")

Output

x is 10

5. Division Assignment

Division assignment operator takes two operands as inputs: x and y, and assigns the quotient in the division of x by y to x.

main.swift

var x = 5
var y = 2
x /= y
print("x is \(x)")

Output

x is 2

In the division of 5/2, 2 is the quotient and 1 is the remainder.

5. Modulus Division Assignment

Modulus Division assignment operator takes two operands as inputs: x and y, and assigns the remainder in the division of x by y to x.

main.swift

var x = 5
var y = 2
x %= y
print("x is \(x)")

Output

x is 1

In the division of 5/2, 2 is the quotient and 1 is the remainder.

Conclusion

In this Swift Tutorial, we learned about Assignment Operators in Swift language, different Assignment operators: Assignment, Addition Assignment, Subtraction Assignment, Multiplication Assignment, Division Assignment, and Modulo Assignment, with examples.