Operators are special symbols that represent an operations performed on data *, such as addition perfomed with the plus sign (+). Operations enable us to *transform our data into something else.
In programming, there are three main types of operators:
arithmetic operators for making calculations,
comparison operators for comparing data,
logical (Boolean) operators for creating logical expressions.
The original purpose of computers was to perform long calculations for us because they are quite tedious and time consuming when performing on a paper.
To perform calculations, we use arithmetic operators like addition (+), subtraction (-), multiplication (*), and division (/).
Addition adds a specific amount to a number like 1 + 2 = 3
Subtraction takes away a specific amount from a number like 3 - 2 = 1
Multiplication takes a number and repeats it a specified number of times like 2 * 3 = 6
Division takes a number and divides it by another number: 6 / 3 = 2
Let’s say you want to store 5 apples in the apples variable. Next, you want to multiply them by two and store the result in a new variable called myApples and finally, you want to subtract 6 apples and store the final result in the finalCount variable:
var apples = 5
var myApples = apples * 2
var finalCount = myApples - 6
Write this code in playground and check out the value of the finalCount variable. It should be equal to 4.
Comparison operators allows us to check if a value is correct or to compare values and evaluate their relationship.
They don’t evaluate to a number, but to boolean values true or false. That’s why they are also known as boolean expressions.
Comparison operators include:
Less than < — value to the left is less than the value to the right: 2 < 10
Greater than > — value to the left is more than the value to the right: 10 > 5
Equals == — value to the left is equal to the value to the right: 3 == 3
Notice how we use a double-equal sign ( == ) to compare values instead of a single-equal sign ( = ) you might know from the math class. That’s because a single-equal sign ( = ) is used in programming to set a value of something, like you would do with a variable, not to compare two values. There’s also the identity operator in Swift ( === ) which checks if two instances of a class point to the same place in memory.
Unlike comparison operators that compare just two values, logical operators allow us to deal with more than two values as they can evaluate multiple boolean expressions.
Logical operators look at several relationships by determining the validity of the overall expression.
Logical operators include:
AND((2 > 1) AND (3 < 4)) is the same as (TRUE AND TRUE). Both expressions evaluate to true, so the final result is also true.
OR((10 > 5) OR (2 > 10)) is the same as (TRUE OR FALSE). One of the expressions evalutes to true, so the final result is true.
NOTNOT (1 < 3) evaluates to NOT (TRUE). The expression always evaluates to the opposite value.