On this lesson, we will break down operators. An operator is a special symbol or phrase that we can use to check, change or combine values.
Terminology
Operators are unary (single target), binary( two targets) or ternary(three targets). The values that operators affect are called operands.
Assignment Operators
We already used this when we were declaring values to variables and constants
let x = 1
var y = 0
y = x
Arithmetic Operators
- Addition (+)
- Substraction (-)
- Multiplication (*)
- and Division (/)
In Swift arithmetic operators don’t allow values to overflow by default.
1 + 1
1 - 1
1 * 1
1 / 1
The addition operator can also be used on String concatenation.
let message = "hey" + " wasup!"
Remainder Operator (%) – if you haven’t use this before, basically it works out how many times x value fits in y and returns the remainder.
var x = 12 % 5 //equals 2
Unary Minus Operator – use to negate a numeric value by prefixing – sign.
let four = 4
let nowNegative = -four // equals -4
Compound Assignment Operators
Compound assignment operators as name suggest combine assignment (=) with another operation.
var x = 0
x += 1 // same as x = x + 1
Comparison Operators
Commonly used on conditional statements and returns a Bool value.
- Equal To ( x == y)
- Not Equal To (x != y)
- Greater than (x > y)
- Less than (x < y)
- Greater than or equal to (x >= y)
- Less than or equal to (x <=)
Sample below all returns true
0 == 0
0 != 1
1 > 0
0 < 1
1 >= 1
1 <= 1
let where = "here"
here == "here" // string comparison
"apple" > "windows" // string comparison
Tuple Comparison – two tuples can be compared if both have same type and number of values. The first element is first compared, if it is false. It ends the comparison.
(1, "apple") > (2, "windows") // returns true - first value of tuple is true