Job-ready Online Courses: Click, Learn, Succeed, Start Now!
In programming, operators play a fundamental role in performing various operations on data. Swift provides a rich set of operators to handle arithmetic, comparison, logical, and other operations. In this article, we will explore Swift operators, their kind and types, and how they contribute to creating efficient and expressive code.
What are Swift Operators?
Swift operators are symbols or special characters used to perform operations on data. Operations such as addition, subtraction, comparison, and more. They act upon one or two operands and produce a result, making it easier to manipulate data in different ways.
Types of Swift Operators
We categorize operators based on the type of operations they perform. Following are the different types of operators.
Arithmetic Operators
Arithmetic operators manage mathematical operations. The below table depicts the arithmetic operators.
| Operator Name | Operator Symbol |
| Addition | + |
| Subtraction | – |
| Multiplication | * |
| Division | / |
| Modulo (Remainder) | % |
var num1 = 8
var num2 = 5
var additionExample = num1 + num2
var subtractionExample = num1 - num2
var multiplicationExample = num1 * num2
var divisionExample = num1 / num2
var moduloExample = num1 % num2
print("Addition:", additionExample)
print("Subtraction:", subtractionExample)
print("Multiplication:", multiplicationExample)
print("Division:", divisionExample)
print("Modulo:", moduloExample)
Output:
Addition: 13
Subtraction: 3
Multiplication: 40
Division: 1
Modulo: 3
Assignment Operators
Assignment Operators assign values to identifiers like variables and constants.
| Operator Name | Operator Symbol |
| Assignment | = |
let example = 2023 //2023 value assigned to example. print(example)
Output:
2023
Compound Assignment Operators
When an arithmetic operator is combined with an assignment operator, it forms a compound assignment operator.
| Operator Name | Operator Symbol |
| Addition Assignment | += |
| Subtraction Assignment | -= |
| Multiplication Assignment | *= |
| Division Assignment | /= |
| Modulo Assignment | %= |
var num1 = 8
var num2 = 5
num1 += num2
print("Addition Assignment:", num1)
num1 -= num2
print("Subtraction Assignment:", num1)
num1 *= num2
print("Multiplication Assignment:", num1)
num1 /= num2
print("Division Assignment:", num1)
num1 %= num2
print("Modulo Assignment:", num1)
Output:
Addition Assignment: 13
Subtraction Assignment: 8
Multiplication Assignment: 40
Division Assignment: 8
Modulo Assignment: 3
Bitwise Operators
Bitwise operators perform operations on each individual bit.
| Operator Name | Operator Symbol |
| Binary AND | & |
| Binary OR | | |
| Binary XOR | ^ |
| Binary NOT | ~ |
| Binary Shift Right | >> |
| Binary Shift Left | << |
var num1 = 2
var num2 = 3
var binaryAnd = num1 & num2
var binaryOr = num1 | num2
var binaryXor = num1 ^ num2
var binaryNot = ~num1
var binaryShiftRight = num1 >> 2
var binaryShiftLeft = num1 << 2
print("AND:", binaryAnd)
print("OR:", binaryOr)
print("XOR:", binaryXor)
print("NOT:", binaryNot)
print("Shift Right:", binaryShiftRight)
print("Shift Left:", binaryShiftLeft)
Output:
AND: 2
OR: 3
XOR: 1
NOT: -3
Shift Right: 0
Shift Left: 8
Shift Operators
Shift operators shift the bits of a number in its binary representation. In Swift, there are two shift operators: Left Shift (<<) and Right Shift (>>) operators.
Left Shift Operator
The left shift operator shifts the bits of a number to the left by the given number of positions. It multiplies the number by 2 to the power of the number of shifts.
Here, a is the number, and b is the number of bits to be shifted.
let originalValue: Int = 3 let leftShiftedValue: Int = originalValue << 2 print(leftShiftedValue)
Output:
12
Right Shift Operator
The right shift operator shifts the bits of a number to the right by the given number of positions. It divides the number by 2 to the power of the number of shifts.
Here, a is the number, and b is the number of bits to be shifted.
let originalValue: Int = 12 let rightShiftedValue: Int = originalValue >> 2 print(rightShiftedValue)
Output:
3
Comparison Operators
Comparison Operators compare two values and return Boolean values.
| Operator Name | Operator Symbol |
| Equal to | == |
| Not Equal to | != |
| Greater than | > |
| Less than | < |
| Greater than or Equal to | >= |
| Less than or Equal to | <= |
let num1 = 2
let num2 = 3
let isEqual = (num1 == num2)
let isNotEqual = (num1 != num2)
let isGreater = (num1 > num2)
let isLess = (num1 < num2)
let isGreaterOrEqual = (num1 >= num2)
let isLessOrEqual = (num1 <= num2)
print("Equal to:", isEqual)
print("Not Equal to:", isNotEqual)
print("Greater than:", isGreater)
print("Less than:", isLess)
print("Greater than or Equal to:", isGreaterOrEqual)
print("Less than or Equal to:", isLessOrEqual)
Output:
Equal to false
Not Equal to true
Greater than false
Less than true
Greater than or Equal to false
Less than or Equal to true
Logical Operators
Logical Operators return boolean values depending on the operand’s value and the operator used.
| Operator Name | Operator Symbol |
| Logical AND | && |
| Logical OR | || |
| Logical NOT | ! |
let value1 = true
let value2 = false
let andValue = value1 && value2
let orValue = value1 || value2
let notValue = !value1
print("AND:", andValue)
print("OR:", orValue)
print("NOT:", notValue)
Output:
AND: false
OR: true
NOT: false
Range Operators
Range Operators run values based on the given range of numbers.
| Operator Name | Operator Symbol |
| Closed Range | (a…b) |
| Half-Open Range | (a..<b) |
| One-Sided Range | [a…] |
for i in 1...5{ //Closed Range
print(i, terminator: " ")
}
print()
for i in 1..<5{ //Half-Open Range
print(i, terminator: " ")
}
print()
let array = [3,5,7,9,10,24]
for i in array[0...]{ //One-sided Range
print(i, terminator: " ")
}
Output:
1 2 3 4 5
1 2 3 4
3 5 7 9 10 24
Miscellaneous Operators
Nil Coalescing Operator
The absence of value is dealt with using the Nil Coalescing Operator. It provides a convenient way to handle optional. It provides a default value in case the optional is nil.
let optionalExampleName: String? = nil
let name = optionalExampleName ?? "Anonymous"
print("Hi, \(name) here.")
Output:
Hi, Anonymous here.
Kinds of Swift Operators
In Swift, operators can be classified into three kinds. They are categorized based on the number of operands they act upon. The three kinds are unary, binary, and ternary operators.
Unary Operator
Unary operators perform operations on a single operand. For example,
1. Logical NOT (!) is a unary operator. It inverts the Boolean value of an identifier.
var isTrue = true var isFalse = !isTrue
2. Unary plus (+) is a unary operator. It represents a positive value.
var number = +2023
Note that it doesn’t change the operand’s value. But it can be used to clarify the positive sign when needed.
3. Unary minus (-) is a unary operator. It represents a negation of a value.
var number = -2023
Note that it changes a positive value to a negative value and vice versa.
Binary Operator
Binary operators operate on two operands. One on the left and the other on the right side of the operator. Swift supports several binary operators such as arithmetic, comparison, logical, etc.
var num1 = 3 var num2 = 2 var sum = (num1 + num2) \\ + is a binary operator.
Ternary Operator
The ternary operator is a special conditional operator. It operates on 3 operands: a condition, a true result and a false result. If the condition is true, then it returns the true result. If the condition is false, it returns a false result.
let year = 2023 let trueOutput = (year == 2023) ? "DataFlair" : "Not DataFlair" print(trueOutput) let falseOutput = (year != 2023) ? "DataFlair" : "Not DataFlair" print(falseOutput)
Output:
DataFlair
Not DataFlair
Operator Precedence
The order in which we evaluate operators when we have multiple operators in one expression is known as Operator Precedence. In the table below, precedence decreases as we go down the table.
| Operator Name | Operator Symbol |
| Bitwise Shift | <<, >> |
| Multiplicative | %, *, / |
| Additive | |, – , +, -, ^ |
| Range | ..<, … |
| Nil-Coalescing | ?? |
| Comparison | <, >, <=, >=, ==. != |
| Logical | &&, || |
| Ternary | ?: |
| Assignment | %=, /=, *=, +=, -= |
let precedenceExample = 2 + 3 * 5 //Based on operator precedence, first multiplication is done and then addition is done. print(precedenceExample)
Output:
17
Conclusion
To wrap up, Swift’s operators are key tools for handling different data operations. They include arithmetic for math, assignments for giving values, comparisons for checking values, and more. By using these symbols, we can perform tasks like addition, subtraction, and comparisons in our code. These swift operators also have priorities based on their precedence.
