Undestanding Swift - Operators


What is an Operator in Swift?

In Swift, operators are special symbols that instruct the compiler to perform specific mathematical, logical, or bitwise operations on one or more operands. These operators make coding more efficient and readable.

For instance, adding two numbers, such as 34 and 21, requires the + operator:

let sum = 30 + 20 // Result: 55

Types of Operators in Swift

Swift provides various categories of operators, each serving a unique purpose:

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Range Operators
  • Miscellaneous Operators

Let's dive into each of these operator types.

1. Swift Arithmetic Operators

Arithmetic operators perform mathematical calculations, such as addition, subtraction, multiplication, and division. These operations require operands of the same type.

Operator Name Example
+ Addition 20 + 30 = 50
- Subtraction 30 - 10 = 20
* Multiplication 10 * 10 = 100
/ Division 20 / 5 = 4
% Modulus 10 % 2 = 0

2. Swift Comparison Operators

Comparison operators compare two values and return a Boolean result (true or false).

Operator Name Example
== Equal 10 == 10 → true
!= Not Equal 34 != 30 → true
> Greater Than 90 > 34 → true
< Less Than 12 < 34 → true
>= Greater Than or Equal To 30 >= 10 → true
<= Less Than or Equal To 10 <= 32 → true

3. Swift Logical Operators

Logical operators help in making decisions based on multiple conditions.

Operator Name Example
&& Logical AND X && Y
|| Logical OR X || Y
! Logical NOT !X

4. Swift Bitwise Operators

Bitwise operators work at the binary level, manipulating individual bits.

Operator Name Example
& Bitwise AND X & Y
| Bitwise OR X | Y
^ Bitwise XOR X ^ Y
~ Bitwise NOT ~X
<< Left Shift X << Y
>> Right Shift X >> Y

5. Swift Assignment Operators

Assignment operators are used to assign or update the value of a variable.

Operator Name Example
= Assignment X = 10
+= Assignment Add X += 12
-= Assignment Subtract X -= 12
*= Assignment Multiply X *= 12
/= Assignment Divide X /= 12
%= Assignment Modulus X %= 12
<<= Assignment Left Shift X <<= 12
>>= Assignment Right Shift X >>= 12
&= Bitwise AND Assignment X &= 12
^= Bitwise XOR Assignment X ^= 12
|= Bitwise OR Assignment X |= 12

6. Swift Miscellaneous Operators

Swift also provides other useful operators that serve specific purposes.

Operator Name Example
- Unary Minus -9
+ Unary Plus +2
? : Ternary Conditional Condition ? X : Y