Operators in Swift

Operator:

An operator is a symbol or combination of symbols that we can use to check, change, or combine values. Swift supports most standard C operators and also improves on some of them to eliminate several common coding errors. For example, the assignment operator does not return a value, which prevents it from being used where we are meant to use the equality operator (==).

Types of Operator in Swift:

There are mainly 7 types of operators in Swift:

1. Arithmetic Operator: The arithmetic operators perform the four basic mathematical operations.
It has the following syntax:

 

Addition:
varA + varB
Subtraction:
varA - varB
Multiplication:
varA * varB
Division:
varA / varB
var x = 4 + 2 //x will equal 6
var x = 4 - 2 //x will equal 2
var x = 4 * 2 //x will equal 8
var x = 4 / 2 //x will equal 2
var x = "Hello " + "world"

 

2. Comparison Operator: The comparison operator returns a Boolean true if the statement is true or a Boolean false if the statement is not true.
It has the following syntax:

Equality:
varA == varB
Not equal:
varA != varB
Greater than:
varA > varB
Less than:
varA < varB Greater than or equal to: varA >= varB
Less than or equal to:
varA <= varB

 

3. Assignment Operator: The assignment operator initializes or updates a variable. It has the following syntax:

var A = var B

4. Ternary Conditional Operator: The ternary conditional operator assigns a value to a variable based on the evaluation of a comparison operator or Boolean value. It has the following syntax:

(boolValue ? valueA : valueB)

5. Compound Assignment Operator: The compound assignment operators combine an arithmetic operator with an assignment operator. It has the following syntax:

varA += varB
varA -= varB
varA *= varB
varA /= varB

6. Remainder Operator: The remainder operator calculates the remainder of the first operand is divided by the second operand. In other languages, this is sometimes referred to as the modulo or modulus operator. It has the following syntax:

varA % varB

7. Logical Operator: Logical operators are mainly used in decision-making. It is used to check whether an expression is true or false.

Example:

var x = 5, y = 6
print((x > 2) && (y >= 6)) // true

where,
&& is the logical operator AND. It checks truly only if both operands are true.