
- Swift - Home
- Swift - Overview
- Swift - Environment
- Swift - Basic Syntax
- Swift - Variables
- Swift - Constants
- Swift - Literals
- Swift - Comments
- Swift Operators
- Swift - Operators
- Swift - Arithmetic Operators
- Swift - Comparison Operators
- Swift - Logical Operators
- Swift - Assignment Operators
- Swift - Bitwise Operators
- Swift - Misc Operators
- Swift Advanced Operators
- Swift - Operator Overloading
- Swift - Arithmetic Overflow Operators
- Swift - Identity Operators
- Swift - Range Operators
- Swift Data Types
- Swift - Data Types
- Swift - Integers
- Swift - Floating-Point Numbers
- Swift - Double
- Swift - Boolean
- Swift - Strings
- Swift - Characters
- Swift - Type Aliases
- Swift - Optionals
- Swift - Tuples
- Swift - Assertions and Precondition
- Swift Control Flow
- Swift - Decision Making
- Swift - if statement
- Swift - if...else if...else Statement
- Swift - if-else Statement
- Swift - nested if statements
- Swift - switch statement
- Swift - Loops
- Swift - for in loop
- Swift - While loop
- Swift - repeat...while loop
- Swift - continue statement
- Swift - break statement
- Swift - fall through statement
- Swift Collections
- Swift - Arrays
- Swift - Sets
- Swift - Dictionaries
- Swift Functions
- Swift - Functions
- Swift - Nested Functions
- Swift - Function Overloading
- Swift - Recursion
- Swift - Higher-Order Functions
- Swift Closures
- Swift - Closures
- Swift-Escaping and Non-escaping closure
- Swift - Auto Closures
- Swift OOps
- Swift - Enumerations
- Swift - Structures
- Swift - Classes
- Swift - Properties
- Swift - Methods
- Swift - Subscripts
- Swift - Inheritance
- Swift-Overriding
- Swift - Initialization
- Swift - Deinitialization
- Swift Advanced
- Swift - ARC Overview
- Swift - Optional Chaining
- Swift - Error handling
- Swift - Concurrency
- Swift - Type Casting
- Swift - Nested Types
- Swift - Extensions
- Swift - Protocols
- Swift - Generics
- Swift - Access Control
- Swift - Function vs Method
- Swift - SwiftyJSON
- Swift - Singleton class
- Swift Random Numbers
- Swift Opaque and Boxed Type
Swift - Operators
Operators are special symbols that perform operations on operands. Operators can be used for various mathematical calculations and logical operations.
What is an Operator in Swift?
An operator is a symbol that tells the compiler to perform specific mathematical or logical operations. Or we can say that operators are special symbols that are used to perform specific operations between one or more operands.
For example, to add two numbers such as 34 and 21 we will use the + operator (34 + 21 = 55).
Type of Swift Operators
Swift supports the following types of operators −
- Arithmetic Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Range Operators
- Misc Operators
Let's discuss each operator separately in detail.
Swift Arithmetic Operators
Arithmetic operators are used to perform mathematic operations like addition, division, multiplication, etc. on the given operands. They always work on two operands but the type of these operands should be the same. Swift supports the following arithmetic operators −
Operator | Name | Example |
---|---|---|
+ | Addition | 20 + 30 = 50 |
- | Subtraction | 30 - 10 = 20 |
* | Multiplication | 10 * 10 = 100 |
/ | Division | 20 / 5 = 4 |
% | Modulus | 10 % 2 = 0 |
Example
Swift program to calculate the total cost of items purchased using arithmetic operators.
import Foundation let item1Price = 120 let item2Price = 80 let quantity1 = 2 let quantity2 = 3 let totalCostItem1 = item1Price * quantity1 let totalCostItem2 = item2Price * quantity2 let totalAmount = totalCostItem1 + totalCostItem2 print("Total cost of item 1: \(totalCostItem1)") print("Total cost of item 2: \(totalCostItem2)") print("Total bill amount: \(totalAmount)")
Output
Total cost of item 1: 240 Total cost of item 2: 240 Total bill amount: 480
Swift Comparison Operators
Comparison operators are used to compare two operands and find the relationship between them. They return the result into a boolean(either true or false). Swift supports the following comparison operators −
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 |
Example
Swift program to compare the prices of two mobile phones using comparison operators.
import Foundation let pricePhoneA = 45000 let pricePhoneB = 50000 print("Phone A is cheaper than Phone B: \(pricePhoneA < pricePhoneB)") print("Phone A and Phone B have the same price: \(pricePhoneA == pricePhoneB)") print("Phone B is more expensive than Phone A: \(pricePhoneB > pricePhoneA)")
Output
Phone A is cheaper than Phone B: true Phone A and Phone B have the same price: false Phone B is more expensive than Phone A: true
Swift Logical Operators
Logical operators are used to perform logical operations between the given expressions. It can also make decisions on multiple conditions. It generally works with Boolean values. Swift supports the following logical operators −
Operator | Name | Example |
---|---|---|
&& | Logical AND | X && Y |
|| | Logical OR | X || Y |
! | Logical NOT | !X |
Example
Swift program to check if a user is eligible for a loan based on age and income using logical operators.
import Foundation let age = 28 let monthlyIncome = 35000 let hasMinimumAge = age >= 21 let hasSufficientIncome = monthlyIncome >= 30000 if hasMinimumAge && hasSufficientIncome { print("Eligible for loan.") } else { print("Not eligible for loan.") } // Using OR and NOT let hasGoodCreditScore = false if hasSufficientIncome || hasGoodCreditScore { print("Eligible based on income or credit score.") } print("Is NOT underage: \(!(age < 18))")
Output
Eligible for loan. Eligible based on income or credit score. Is NOT underage: true
Swift Bitwise Operators
Bitwise operators are used to manipulate individual bits of the integer. They are commonly used to perform bit-level operations. Swift supports the following bitwise operators −
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 |
Example
Swift program to demonstrate bitwise operations using two integer values representing access permissions.
import Foundation let readPermission: UInt8 = 0b0001 // 1 let writePermission: UInt8 = 0b0010 // 2 let fullAccess = readPermission | writePermission let hasRead = (fullAccess & readPermission) != 0 let hasWrite = (fullAccess & writePermission) != 0 let inverted = ~readPermission print("Full access (read | write): \(fullAccess)") print("Has read permission: \(hasRead)") print("Has write permission: \(hasWrite)") print("Inverted read permission: \(inverted)")
Output
Full access (read | write): 3 Has read permission: true Has write permission: true Inverted read permission: 254
Swift Assignment Operators
Assignment operators are used to assign and update the value of the given variable with the new value. Swift supports the following assignment operators −
Operator | Name | Example |
---|---|---|
(=) | Assignment | X = 10 |
+= | Assignment Add | X = X + 12 |
-= | Assignment Subtract | X = X - 12 |
*= | Assignment Multiply | X = X * 12 |
/= | Assignment Divide | X = X / 12 |
%= | Assignment Modulus | X = X % 12 |
<<= | Assignment Left Shift | X = X << 12 |
>>= | Assignment Right Shift | X = X >> 12 |
&= | Bitwise AND Assignment | X = X & 12 |
^= | Bitwise Exclusive OR Assignment | X = X ^12 |
|= | Bitwise Inclusive OR Assignment | X = X | 12 |
Example
Swift program to calculate and update a savings account balance using assignment operators.
import Foundation var savings = 10000 // Deposit amount savings += 5000 // Add 5000 print("After deposit, savings: \(savings)") // Withdrawal amount savings -= 2000 // Subtract 2000 print("After withdrawal, savings: \(savings)") // Apply 10% interest savings *= 110 savings /= 100 print("After applying interest, savings: \(savings)")
Output
After deposit, savings: 15000 After withdrawal, savings: 13000 After applying interest, savings: 14300
Swift Misc Operators
Apart from the general operators Swift also supports some special operators (miscellaneous operators) and they are −
Operator | Name | Example |
---|---|---|
- | Unary Minus | -9 |
+ | Unary Plus | 2 |
Condition ? X : Y | Ternary Conditional | If Condition is true ? Then value X : Otherwise value Y |
Example
Swift program demonstrating unary minus and plus to adjust temperatures, and the ternary operator to check if the temperature is comfortable.
import Foundation var currentTemperature = 25 let temperatureChange = -5 // Unary minus let newTemperature = currentTemperature + (-temperatureChange) // increases by 5 print("New Temperature: \(newTemperature) Degree Celsius") // Unary plus let adjustedTemperature = +newTemperature //no effect print("Adjusted Temperature: \(adjustedTemperature) Degree Celsius") // Ternary operator to check comfort let comfort = (adjustedTemperature >= 20 && adjustedTemperature <= 30) ? "Comfortable" : "Uncomfortable" print("Temperature is: \(comfort)")
Output
New Temperature: 30 Degree Celsius Adjusted Temperature: 30 Degree Celsius Temperature is: Comfortable
Swift Advance Operators
Apart from the basic operators Swift also provides some advanced operators that are used to manipulate complex values and they are −
- Arithmetic Overflow Operators
- Identity Operators
- Range Operators
Let's discuss each operator separately in detail.
Swift Arithmetic Overflow Operators
Arithmetic overflow operators are used to perform arithmetic operations and handle overflow very well if occurs. Or we can say that arithmetic operators work with those integers whose value may exceed the maximum or minimum bound. Swift supports the following arithmetic overflow operators −
Operator | Name | Example |
---|---|---|
&+ | Overflow Addition | Num1 &+ Num2 |
&- | Overflow Subtraction | Num1 &- Num2 |
&* | Overflow Multiplication | Num1 &* Num2 |
Swift Identity Operators
Identity operators are used to determine whether the given variable refers to the same instance or not. These operators work with objects and classes. They are referenced type operators. Swift supports the following type of identity operators −
Operator | Name | Example |
---|---|---|
+=== | Identical to | Value1 === Value2 |
!== | Not Identical to | Value2 !== Value2 |
Swift Range Operators
Range operators are used to define ranges. They are used in loops, collections and control flow statements. Swift supports the following range operators −
Operator | Name | Example |
---|---|---|
XY | Closed Range | 13 = 1, 2, 3 |
X..<Y | Half Open Range | 1..<3 = 1, 2 |
X Or X | One Side Range | 2 = 2, 3, 4, |
Swift Operator Precedence
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, and those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Name | Operator | Precedence |
---|---|---|
Primary Expression Operators | () [] . expr++ expr-- | left-to-right |
Unary Operators |
* & + - ! ~ ++expr --expr * / % + - >> << < > <= >= == != |
right-to-left |
Binary Operators | & ^ | && || | left-to-right |
Ternary Operator | ?: | right-to-left |
Assignment Operators | (= += -= *= /= %= >>= <<= &= ^= |=) | right-to-left |
Comma | , | left-to-right |