Operators in Swift, In computer programming, operators are constructs defined within programming languages that behave generally like functions, but which differ syntactically or semantically. Common simple examples include arithmetic, comparison, and logical operations.
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
- Arithmetic operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- Misc Operators
Arithmetic operators are used to performing mathematical operations like addition, subtraction, multiplication, etc.
#Example var a = 7 var b = 2 // addition print (a + b) // subtraction print (a - b) // multiplication print (a * b)
Assignment operators are used to assign values to variables.
|=||C = A + B will assign value of A + B into C|
|+=||C += A is equivalent to C = C + A|
|-=||C -= A is equivalent to C = C – A|
|*=||C *= A is equivalent to C = C * A|
|/=||C /= A is equivalent to C = C / A|
|%=||C %= A is equivalent to C = C % A|
|<<=||C <<= 2 is same as C = C << 2|
|>>=||C >>= 2 is same as C = C >> 2|
|&=||C &= 2 is same as C = C & 2|
|^=||C ^= 2 is same as C = C ^ 2|
||=||C |= 2 is same as C = C | 2|
#Example // assign 10 to a var a = 10 // assign 5 to b var b = 5 // assign the sum of a and b to a a += b // a = a + b print(a)
Comparison operators compare two values/variables and return a boolean result: true or false.
|==||Is Equal To|
|!=||Not Equal To|
|>=||Greater Than or Equal To|
|<=||Less Than or Equal To|
#Example var a = 5, b = 2 // equal to operator print(a == b) // not equal to operator print(a != b) // greater than operator print(a > b) // less than operator print(a < b) // greater than or equal to operator print(a >= b) // less than or equal to operator print(a <= b)
Logical operators are used to check whether an expression is true or false. They are used in decision-making.
|&&||a && b|
|||||a || b|
// logical AND print(true && true) // true print(true && false) // false // logical OR print(true || false) // true // logical NOT print(!true) // false
In Swift, bitwise operators are used to performing operations on individual bits.
|~||Binary One’s Complement|
|<<||Binary Shift Left|
|>>||Binary Shift Right|
Here’s a list of other operators available in Swift.
|? :||(5 > 2) ? “Success” : “Error” // Success|
|??||number ?? 5|
|…||1…3 // range containing values 1,2,3|
Happy Swift Coding 🙂