Easy Tutorial
❮ Swift Type Casting Swift Optional Chaining ❯

Swift Operators

An operator is a symbol that tells the compiler to perform a mathematical or logical operation.

Swift provides the following types of operators:

In this section, we will detail arithmetic operators, relational operators, logical operators, bitwise operators, assignment operators, and other operators.


Arithmetic Operators

The following table lists the arithmetic operators supported by Swift, with variable A set to 10 and variable B set to 20:

Operator Description Example
+ Addition A + B results in 30
Subtraction A − B results in -10
* Multiplication A * B results in 200
/ Division B / A results in 2
% Modulus B % A results in 0

Note: The ++ and -- operators have been removed in Swift 3.

Example

Here is a simple example of arithmetic operations:

import Cocoa

var A = 10
var B = 20

print("A + B results in: \(A + B)")
print("A - B results in: \(A - B)")
print("A * B results in: \(A * B)")
print("B / A results in: \(B / A)")
A += 1   // Similar to A++
print("A += 1 results in A being \(A)")
B -= 1   // Similar to B--
print("B -= 1 results in B being \(B)")

The output of the above program is:

A + B results in: 30
A - B results in: -10
A * B results in: 200
B / A results in: 2
A += 1 results in A being 11
B -= 1 results in B being 19

Comparison Operators

The following table lists the comparison operators supported by Swift, with variable A set to 10 and variable B set to 20:

Operator Description Example
== Equal to (A == B) is false.
!= Not equal to (A != B) is true.
> Greater than (A > B) is false.
< Less than (A < B) is true.
>= Greater than or equal to (A >= B) is false.
<= Less than or equal to (A <= B) is true.

Example

Here is a simple example of comparison operations:

import Cocoa

var A = 10
var B = 20

print("A == B results in: \(A == B)")
print("A != B results in: \(A != B)")
print("A > B results in: \(A > B)")
print("A < B results in: \(A < B)")
print("A >= B results in: \(A >= B)")
print("A <= B results in: \(A <= B)")

The output of the above program is:

A == B results in: false
A != B results in: true
A > B results in: false
A < B results in: true
A >= B results in: false
A <= B results in: true

Logical Operators

The following table lists the logical operators supported by Swift, with variable A set to true and variable B set to false:

Operator Description Example
&& Logical AND. If both sides of the operator are TRUE, then the condition is TRUE. (A && B) is false.
Logical OR. If at least one side of the operator is TRUE, then the condition is TRUE. (A B) is true.
! Logical NOT. Reverses the logical state of its operand. !(A && B) is true.

Here is a simple example of logical operations:

import Cocoa

var A = true
var B = false

print("A && B results in: \(A && B)")
print("A || B results in: \(A || B)")
print("!A results in: \(!A)")
print("!B results in: \(!B)")

The output of the above program is:

A && B results in: false
A || B results in: true
!A results in: false
!B results in: true

Bitwise Operators

Bitwise operators operate on binary representations. The operators ~, &, |, and ^ are for NOT, AND, OR, and XOR operations, respectively, as shown in the table below:

| p | q | p & q | p | q | p ^ q | This is an example of bitwise operations with specified variables A = 60 and B = 13, represented in binary:

A = 0011 1100
B = 0000 1101

Bitwise operations:

Operator Description Example
& Bitwise AND. Returns a new number where each bit is set to 1 if both corresponding bits of the input numbers are 1. (A & B) results in 12, binary 0000 1100
| Bitwise OR. Returns a new number where each bit is set to 1 if at least one of the corresponding bits of the input numbers is 1. (A | B) results in 61, binary 0011 1101
^ Bitwise XOR. Returns a new number where each bit is set to 1 if only one of the corresponding bits of the input numbers is 1. (A ^ B) results in 49, binary 0011 0001
~ Bitwise NOT. Inverts all the bits of the operand. (~A) results in -61, binary 1100 0011 in 2's complement form
<< Bitwise left shift. Shifts all bits of the operand to the left by the specified number of positions. A << 2 results in 240, binary 1111 0000
>> Bitwise right shift. Shifts all bits of the operand to the right by the specified number of positions. A >> 2 results in 15, binary 0000 1111

Simple example of bitwise operations:

import Cocoa

var A = 60  // Binary 0011 1100
var B = 13  // Binary 0000 1101

print("A&B result: \(A&B)")
print("A|B result: \(A|B)")
print("A^B result: \(A^B)")
print("~A result: \(~A)")

Output of the above program:

A&B result: 12
A|B result: 61
A^B result: 49
~A result: -61

Assignment Operations

Basic assignment operators in Swift:

Operator Description Example
= Simple assignment operator. Assigns the value of the right operand to the left operand. C = A + B assigns the result of A + B to C
+= Add AND assignment operator. Adds the right operand to the left operand and assigns the result to the left operand. C += A is equivalent to C = C + A
-= Subtract AND assignment operator. Subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A
*= Multiply AND assignment operator. Multiplies the right operand with the left operand and assigns the result to the left operand. C *= A is equivalent to C = C * A
/= Divide AND assignment operator. Divides the left operand by the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A
%= Modulus AND assignment operator. Takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is equivalent to C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is equivalent to C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is equivalent to C = C & 2
^= Bitwise XOR AND assignment operator. C ^= 2 is equivalent to C = C ^ 2
|= Bitwise OR AND assignment operator. C |= 2 is equivalent to C = C | 2

Simple example of assignment operations:

import Cocoa

var A = 10
var B = 20
var C = 100

C = A + B
print("C result: \(C)")

C += A
print("C result: \(C)")

C -= A
print("C result: \(C)")

C *= A
print("C result: \(C)")

C /= A print("C result is: (C)")

// The following tests are commented out and can be uncommented to test each instance /* C %= A print("C result is: (C)")

C <<= A print("C result is: (C)")

C >>= A print("C result is: (C)")

C &= A print("C result is: (C)")

C ^= A print("C result is: (C)")

C |= A print("C result is: (C)") */

The above program execution results are:

C result is: 30
C result is: 40
C result is: 30
C result is: 300
C result is: 30

Range Operators

Swift provides two range operators.

Operator Description Example
Closed Range Operator The closed range operator (a...b) defines a range that runs from a to b, including both a and b, where b must be greater than or equal to a. The closed range operator is useful when iterating over a range of values, such as in a for-in loop: 1...5 range values are 1, 2, 3, 4, and 5
Half-Open Range Operator The half-open range operator (a..<b) defines a range from a to b, but does not include b. It is called half-open because it includes the first value but not the last value. 1..<5 range values are 1, 2, 3, and 4

Here is a simple example of range operations:

import Cocoa

print("Closed Range Operator:")
for index in 1...5 {
    print("\(index) * 5 = \(index * 5)")
}

print("Half-Open Range Operator:")
for index in 1..&lt;5 {
    print("\(index) * 5 = \(index * 5)")
}

The above program execution results are:

Closed Range Operator:
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
Half-Open Range Operator:
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20

Other Operators

Swift provides other types of operators, such as unary, binary, and ternary operators.

Operator Description Example
Unary Minus Prefix - sign before a number -3 or -4
Unary Plus Prefix + sign before a number +6 results in 6
Ternary Conditional condition ? X : Y If condition is true, the value is X; otherwise, it is Y

Here is a simple example of unary, binary, and ternary operations:

import Cocoa

var A = 1
var B = 2
var C = true
var D = false
print("-A value is: \(-A)")
print("A + B value is: \(A + B)")
print("Ternary operation: \(C ? A : B )")
print("Ternary operation: \(D ? A : B )")

The above program execution results are:

-A value is: -1
A + B value is: 3
Ternary operation: 1
Ternary operation: 2

Operator Precedence

In an expression, there may be multiple data objects connected by different operators with different data types. Since an expression can involve multiple operations, different order of operations can lead to different results or even erroneous calculations. Therefore, it is necessary to combine operations in a certain order to ensure the reasonableness and correctness of the results.

Precedence decreases from top to bottom, with the top having the highest precedence, and the comma operator having the lowest precedence.

Within the same precedence level, calculations are performed according to the binding order. Most operations are calculated from left to right, except for three levels that are calculated from right to left, which are unary operators, conditional operators, and assignment operators.

The basic precedence rules to remember are:

Swift operator precedence (from highest to lowest):

Operator Example
Bitwise Operators >> &<< &>> >>
Multiplicative Operators &* % & * /
Addition Operators &+ &- + - ^
Range Operators ..< ...
Type Casting Operators is as
Nil-Coalescing Operator ??
Comparison Operators != > < >= <= === ==
Logical AND Operator &&
Logical OR Operator
Tilde Arrow ~>
Ternary Conditional Operator ?:
Arrow Function ( )
Assignment Operators = %= /= &<<= &>>= &= *= >>= <<= ^= += -=

Here is a simple example of operator precedence:

import Cocoa

var A = 0

A = 2 + 3 * 4 % 5
print("The value of A is: \(A)")

The output of the above program is:

The value of A is: 4

Example Analysis:

Based on operator precedence, the above program can be broken down into the following steps, equivalent to:

2 + ((3 * 4) % 5)

First step calculation: (3 * 4) = 12, so the expression becomes:

2 + (12 % 5)

Second step calculation: 12 % 5 = 2, so the expression becomes:

2 + 2

At this point, it is easy to see that the result is 4.

❮ Swift Type Casting Swift Optional Chaining ❯