Demo 1
Demo 1
Demo 1
print(5 + 6) // 11
Types of Operators
Here's a list of different types of Swift operators that you will learn in this
tutorial.
1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Other Operators
+ Addition 5 + 2 = 7
- Subtraction 4 - 2 = 2
* Multiplication 2 * 3 = 6
/ Division 4 / 2 = 2
% Modulo 5 % 2 = 1
var a = 7
var b = 2
// addition
print (a + b)
// subtraction
print (a - b)
// multiplication
print (a * b)
Output
9
5
14
- to subtract b from a
* to multiply a and b
/ Division Operator
The / operator performs division between two numbers. However, if two
numbers are integers, we will only get the quotient. For example,
If we use the / operator with floating-point numbers, we will get the actual
result. For example,
// perform division
7.0 / 3.0 = 3.5
% Modulo Operator
The modulo operator % computes the remainder. For example,
print(9 % 4) // 1
// assign 5 to x
var x = 5
= Assignment Operator a = 7
+= Addition Assignment a += 1 // a = a + 1
-= Subtraction Assignment a -= 3 // a = a - 3
*= Multiplication Assignment a *= 4 // a = a * 4
/= Division Assignment a /= 3 // a = a / 3
%= Remainder Assignment a %= 10 // a = a % 10
// assign 10 to a
var a = 10
// assign 5 to b
var b = 5
print(a)
Output
15
3. Swift Comparison Operators
Comparison operators compare two values/variables and return a boolean
result: true or false . For example,
var a = 5, b =2
print (a > b) // true
var a = 5, b = 2
// equal to operator
print(a == b)
Output
false
true
true
false
true
false
var a = 5, b = 6
print((a > 2) && (b >= 6)) // true
Here, && is the logical operator AND. Since both a > 2 and b >= 6 are true ,
Logical AND:
&& a && b
true only if both the operands are true
Logical OR:
|| a || b
true if at least one of the operands is true
Logical NOT:
! !a
true if the operand is false and vice-versa.
// logical AND
print(true && true) // true
print(true && false) // false
// logical OR
print(true || false) // true
// logical NOT
print(!true) // false
Output
true
false
true
false
Operator Description
| Binary OR
^ Binary XOR