
Arithmetic operators are used to perform mathematical operations.
Mathematical operations, not supported by arithmetic operators, can be performed using SWIFT mathematical functions.
Arithmetic
//TEST VARIABLES.
var x = 10
var y = 20
//ARITHMETIC OPERATORS.
var negate = -y // Negation -20 = -20
var add = x + y // Addition 10+20 = 30
var subtract = x - y // Subtraction 10-20 = -10
var multiply = x * y // Multiplication 10*20 = 200
var divide = x / y // Division 10/20 = 0.5
var modulo = x % y // Modulus 10%20 = 0*20+10 = 10
y += 5 // Increment by 5
y -= 5 // Decrement by 5
Logical operators are used to combine boolean values that can be only TRUE or FALSE.
This way they provide a method to direct program flow depending on the outcome.
Logical
//TEST VARIABLES.
var left = 65
var right = 70
//LOGICAL OPERATORS.
if ( !(left == 80)) { print("left is NOT equal to 80 \n") } // NOT True if b is not true
if ( left > 50 && right == 70 ) { print("left >50 AND right==70 \n") } // AND True if both are true
if ( left != 50 || right > 90 ) { print("left!=50 OR right> 90 \n") } // OR True if either is true
Bitwise operators combine bits within one or two integers.
Left shift <<n is Arithmetic Shift equivalent of multiplying by 2
n
which preserves operand sign.
Right shift >>n is Arithmetic Shift equivalent of dividing by 2
n
which preserves operand sign.
AND, OR, XOR and NOT do not change the value of operands.
Bitwise
//TEST VARIABLES.
var left = 27 //11011
var right = 18 //10010
//BITWISE OPERATORS.
var and = left & right //10010. 1 if both bits are 1.
var or = left | right //11011. 1 if either bit is 1.
var xor = left ^ right //01001. 1 if bits are different.
var invert = ~left //11111111111111111111111111100100. Invert bits.
var shiftLeft = left << 3 //11011000. Shift bits to left by 3 positions. Fill with 0.
var shiftRight = left >> 2 //110. Shift bits to right by 2 positions. Fill with sign bit.
//DISPLAY RESULTS.
print(and)