Swift Advanced Operators (Bitwise, Overflow, Equivalence, Prefix, Postfix)

In addition to basic operators, swift provides several advanced operators (bitwise and bit shifting) to perform more complex operations. In swift, Arithmetic operators won’t show the overflow value by default. To opt the behavior of overflow, swift uses the second set of advanced operators such as the addition operators (+&) and all these operators are beginning with (&). By using these operators in our own structures, enumerations, and classes we can easily determine the behavior of each type.

Swift Bitwise Operators

In swift, Bitwise operators enable us to work with raw data bits to perform bit by bit operation on the data structure. Generally, these types of operators are useful in assembly language, graphics programming and etc. These bitwise operators are very useful when we apply the encoding and decoding technique to our communication operators.

 

The following are the bitwise operators which support in a swift programming language.

Swift Bitwise NOT Operator

In swift, Bitwise NOT Operator (~) will invert all bits in input number like if we have a positive bit (1) it inverts into negative (0) and vice versa.

 

Following is the pictorial representation of bitwise not operator (~) in a swift programming language.

 

Swift Bitwise Not Operator with Examples

Swift Bitwise Not Operator Syntax

Generally, the bitwise not operator is a prefix operator which appears before the value it operates on, without having any whitespace.

 

Following is the syntax of defining a Bitwise NOT operator in a swift programming language.

 

~"Expression"

Here is the example of using Bitwise NOT operator in a swift programming language.

 

let intialBits : UInt8 = 0b11110000

let invertBit = ~intialBits  // equals to 00001111

print(intialBits)

print(invertBit)

If you observe the above example we defined a constant initialBits with UInt8 data type. The UInt8 integer will have eight bits and can store any value between 0 and 255. In our example, we defined a value “11110000”. The 11110000 value will be equals to the decimal value of 240.

 

The Bitwise NOT operator will convert all zero’s (0) to ones (1). The value of InitialBit is 00001111, which is equal to the decimal value of 15.

 

When we run above example in swift playground we will get a result like as shown below

 

240

15

This is how we can use Bitwise NOT operator in a swift programming language to invert bit values based on our requirements.

Swift Bitwise AND Operator

In swift, Bitwise AND operator (&) is useful to compare the bits of two input numbers. The Bitwise AND operator will return the result as 1 only when both input bits are equals to 1 otherwise it will return 0.

 

Following is the pictorial representation of swift Bitwise AND operator. Here we are comparing two input numbers Input A and Input B to return the result using Bitwise AND operator.

 

Swift Bitwise AND Operator with Examples

Swift Bitwise AND Operator Syntax

Generally, in swift Bitwise AND operator (&) is used to compare two input values and it returns the result as 1 only when both input bits are having a value 1 otherwise it will return 0.

 

Following is the syntax of defining a Bitwise AND operator in a swift programming language.

 

"input1" & "input2"

Here is the example of using Bitwise AND operator in a swift programming language.

 

let inputA : UInt8 = 0b00000110

let inputB : UInt8 = 0b00000101

let result = inputA & inputB // equals to 00000100

print(result)

If you observe above example we defined a constant inputA and inputB with UInt8 data type. The UInt8 integer will have an eight bits and can store any value between 0 and 255. In our example we assigned an inputA as “00000110” and inputB as “00000101”.

 

The Bitwise AND operator will compare two input numbers and return 1 only when both numbers having one (1). The value of the result is 00000100, which is equal to the decimal value of 4.

 

When we run above example in swift playground we will get a result like as shown below

 

4

This is how we can use Bitwise AND operator in a swift programming language to compare two input numbers based on our requirements.

Swift Bitwise OR Operator

In swift, Bitwise OR operator (|) is used to compare the bits of two input numbers. The Bitwise OR operator returns 1 only when any one of the input bit is equal to 1 otherwise it will return 0.

 

Following is the pictorial representation of swift Bitwise OR operator. Here we are comparing two input numbers Input A and Input B to return the result using Bitwise OR operator.

 

Swift Bitwise OR Operator with Examples

Swift Bitwise OR Operator Syntax

Following is the syntax of defining a Bitwise OR operator in a swift programming language.

 

"input1" | "input2"

Here is the example of using Bitwise OR operator in a swift programming language.

 

let inputA : UInt8 = 0b00000110

let inputB : UInt8 = 0b00000100

let result = inputA | inputB   // equals to 00000110

print(result)

If you observe above example we defined a constant inputA and inputB with UInt8 data type. The UInt8 integer will have an eight bits and can store any value between 0 and 255. In our example we assigned an inputA as “00000110” and inputB as “00000100”.

 

The Bitwise OR operator will compare two input numbers and return 1 if any one of the input number is having one (1). The value of the result is 00000110, which is equal to a decimal value of 6.

 

When we run above example in swift playground we will get a result like as shown below

 

6

This is how we can use Bitwise OR operator in a swift programming language to compare two input numbers based on our requirements.

Swift Bitwise XOR Operator

In swift, Bitwise XOR operator or Exclusive OR operator (^) is useful to compare the bits of two numbers. The Bitwise XOR operator returns 1 only when input bits are different and it returns 0 incase input bits are the same.

 

Following is the pictorial representation of the swift Bitwise XOR operator. Here we are comparing two input numbers Input A and Input B to return the result using Bitwise XOR operator.

 

Swift Bitwise XOR Operator with Examples

Swift Bitwise XOR Operator Syntax

Following is the syntax of defining a Bitwise XOR operator in a swift programming language.

 

"input1" ^ "input2"

Here is the example of using Bitwise XOR operator in a swift programming language.

 

let inputA : UInt8 = 0b00000110

let inputB : UInt8 = 0b01000100

let result = inputA ^ inputB  // equals to 01000010

print(result)

If you observe above example we defined a constant inputA and inputB with UInt8 data type. The UInt8 integer will have an eight bits and can store any value between 0 and 255. In our example we assigned an inputA as “00000110” and inputB as “01000100”.

 

The Bitwise XOR operator will compare two input numbers and return 1 if any one of the input numbers having one (1). The value of the result is 01000010, which is equal to the decimal value of 2.

 

When we run above example in swift playground we will get a result like as shown below

 

2

This is how we can use the Bitwise XOR operator in a swift programming language to compare two input numbers based on our requirements.

Swift Bitwise Left and Right Shift Operators

In swift, Bitwise Left (<<) and Bitwise Right (>>) operators are used to move all the bits in a number to right or left by a certain number of places according to the rule.

 

In swift, bitwise shifting behavior causes the following things.

 

  1. Bits are moved on request to left or right by the requested number of places.
  2. Any bits that are moved out of the integer storage are discarded.
  3. Zero is inserted in the spaces left behind after the original bits are moved to the left or right.

Following is the pictorial representation performing bitwise left shift and bitwise right shift operators in a swift programming language. 

 

Here we are performing bitwise left shift 11111101 << 1 (Shifting 11111101 to left by 1 place) and right shift 11111011 >> 1 (Shifting 11111011 to right by 1 place) operations.

 

Swift Bitwise Left Shift and Right Shift Operators with Examples

 

In the above picture, Blue numbers are shifted, Gray numbers are discarded and Orange zeros are newly inserted.

Swift Bitwise Left and Right Shift Operators Syntax

Generally in swift left and right shift operators are used to shift the position of numbers either to left or right based on requirements.

 

Following is the syntax of defining left and right shift operators in a swift programming language.

 

"Expression" << Value

"Expression" >> Value

Here is the example of using left and right shift operators to shift numbers either right or left based on the defined number of positions in a swift programming language.

 

let inputA: UInt8 = 0b00000110

print(inputA << 1) // equals to 00001100

print(inputA << 2) // equals to 00011000

print(inputA << 5) // equals to 11000000

print(inputA >> 3) // equals to 00000000

print(inputA << 7) // equals to 00000000

If you observe above example we defined a constant inputA with UInt8 data type. The UInt8 integer will have an eight bits and can store any value between 0 and 255. In our example we assigned an inputA as “00000110” and we are shifting inputA value to left and right based on our requirements.

 

The Bitwise Left and Right operators will shift input number to either left or right based on the defined number positions.

 

When we run above example in swift playground we will get decimal values of a result like as shown below

 

12

24

192

This is how we can use Bitwise Left and Right shift operators to shift the position of numbers either to left or right based on our requirements in a swift programming language.

Swift Overflow Operator

In swift, when we try to insert a too large or too small number into a constant or variable integer that cannot hold that value, by default Swift will throw an error instead of allowing to create an invalid value. The overflow operator is helpful when we need to work with numbers that are too small or large.

 

Here is the example in which int32 holds the integers range between -2147483648 to 2147483647. In case if we try to set int32 constant or variable value outside of this range causes an error.

 

var num = Int32.max // equals to 2147483647

num += 1

print(num)

When we run the above program in swift playground we will get a result like as shown below

 

integer integral overflows when stored into Int32.

Here we tried to set num variable value outside of the Int32 range (-2147483648, 2147483647) that’s the reason we got the error. 

Swift provides three types of operators to handle errors when values get too large or too small. By using these operators we can opt into the overflow behavior for integer calculations instead of throwing an error. 

 

The following are the overflow operators available in a swift programming language. All these operators will begin with an ampersand (&).

 

  • Overflow Subtraction (&-)
  • Overflow Addition (&+)
  • Overflow Multiplication (&*) 

Swift Value Overflow

In swift, numbers can overflow either in a negative or positive direction. Following is the example of overflow an integer value in a positive direction using an overflow addition operator (&+) to handle overflow exceptions.

 

var overflownum = UInt8.max

overflownum = overflownum &+ 1

print(overflownum)

If you observe above example we initialized a variable overflownum with the maximum value (255 or 11111111 in binary) of UInt8 type and increasing a variable value by 1 using overflow addition operator (&+).

 

When we run above example in swift playground we will get a result like as shown below

 

0

When we increase a variable value it causes to overflow the size of UInt8 type but overflow addition operator (&+) hold the value within the bounds of the UInt8 type and it returns a 00000000 or 0.

 

Following is the example of overflow an integer value in a negative direction using an overflow subtraction operator (&-) to handle overflow exceptions.

 

var overflownum = UInt8.min

overflownum = overflownum &- 1

print(overflownum)

When we run above example in swift playground we will get a result like as shown below

 

255

The minimum value of UInt8 can hold is 0 or 0000000 in binary. If we subtract 1 from 00000000 using overflow subtraction operator (&-), the number will overflow to 11111111 or 255 in decimal.

Swift Operators Precedence and Associativity

Generally, in swift Operator Precedence means giving a high priority to some operators and these operators will apply first.

 

Operator Associativity defines how operators of the same precedence are grouped together, either grouped from the left side or right side.

 

Here is the example of the precedence and associativity of operators in a swift programming language.

 

var result = 34 + 2 % 6 * // Equals to 40

print(result)

When we run the above program in swift playground we will get a result like as shown below

 

40

If we read from left to right it needs to return 18 but the result is 40 because higher precedence operators will evaluate first then lower precedence operators will execute.

 

In swift, the remainder (%) and multiplication (*) operators have higher precedence than addition (+) operator due to that remainder and multiplication operators will evaluate first then addition operation will perform.

 

The remainder (%) and multiplication (*) operators have the same precedence in that case we need to consider the associativity of operators. Here both remainder and multiplication operators are associated with the expression to their left so the expression will start from their left like as shown below

 

34 + ((2 % 6) * 3)

Here (2 % 6) equals to 2 so the above expression will be equals to

 

34 + (2 * 3)

Here (2 * 3) equals to 6 so the above expression will be equals to 

 

34 + 6

Finally, it will return the result as 40

 

This is how operator precedence and associativity will work to evaluate expressions in a swift programming language based on our requirements.

Swift Operator Methods

Operator methods allow us to declare the method which performs a special type of task. Structures and classes provide their own implementation in their existing operators. This is known as the overloading of the operator. 

 

Following is the example to overload subtraction (-) sign and convert our positive integer into a negative integer in a swift programming language.

 

struct Conversion {

var number = 0.0

}

prefix func - (ConvertNum: Conversion) -> Conversion {

return Conversion(number: -ConvertNum.number)

}

let pos = Conversion(number: 5.0)

print(pos)

let neg = -pos

print(neg)

If you observe above example we are overloading an operator (-) and implementing custom functionality.

 

When we run the above program in swift playground we will get a result like as shown below

 

Conversion(number: 5.0)

Conversion(number: -5.0)

This is how we can use operator methods in a swift programming language based on our requirements.

Swift Prefix and Postfix Operators

Generally, in swift the prefix and postfix operators can work with a single target. If we prefix an operator just before the target (-x) is called a prefix operation and in postfix operation operators follow their target (x-).

 

In swift, we can implement prefix and postfix operations by using prefix and postfix modifiers just before the func keyword like as shown below

 

prefix func - (ConvertNum: Conversion) -> Conversion {

return Conversion(number: -ConvertNum.number)

}

Following is the example of defining prefix operator using prefix modifier in swift programming language.

 

struct Conversion {

var number = 0.0

}

prefix func - (ConvertNum: Conversion) -> Conversion {

return Conversion(number: -ConvertNum.number)

}

let pos = Conversion(number: -5.0)

print(pos)

let neg = -pos

print(neg)

If you observe above example we implemented a simple prefix operation to convert given numeric values into negative equivalent and vice versa.

 

When we run the above program in swift playground we will get a result like as shown below

 

Conversion(number: -5.0)

Conversion(number: 5.0)

This is how we can implement prefix and postfix operations in a swift programming language based on our requirements.

Swift Compound Assignment Operator

In swift, computer assignment operator means it’s a combination of assignment (=) operator with another operation. For example, the addition assignment operator (+=) is a combination of addition (+) and assignment (=) into a single operation. 

 

In swift, we need to mark a compound assignment operator left input parameter type as inout, because the parameter value will be modified directly from the operator method.

 

Following is the example of implementing an addition assignment operator in a swift programming language.

 

struct addop {

var x = 0.0, y = 0.0

}

extension addop {

static func += (left: inout addop, right: addop) {

left = left + right

}

}

var num1 = addop(x: 4, y: 5)

var num2 = addop(x: 15, y: 10)

num1 += num2

print(num1)

When we run above example in swift playground we will get a result like as shown below

 

addop(x: 19.0, y: 15.0)

This is how we can use compound assignment operators in a swift programming language to combine assignment (=) with other operations.

Swift Equivalence Operator

Sometimes we need custom operators to check or confirm the type of our implementation. The custom functions in swift won’t receive default implementation of equivalence operators, known as equal to the operator (==) and not equal to the operator (!=) to know our own custom type is equal or not.

 

Following is the example of using equivalence operators to check for equivalence of our own custom type in a swift programming language.

 

struct Equalop {

var x = 0.0, y = 0.0

}

extension Equalop {

static func == (left: Equalop, right: Equalop) -> Bool {

return (left.x == right.x) && (left.y == right.y)

}

static func != (left: Equalop, right: Equalop) -> Bool {

return !(left == right)

}

}

var num1 = Equalop(x: 4, y: 5)

var num2 = Equalop(x: 15, y: 10)

if num1 == num2 {

print("Both are Equal")

}

else if num1 != num2 {

print("Both are Not Equal")

}

If you observe above example we implemented a “equal to (==)” and “not equal to (!=)” operators to check if two Equalop instances have equal values or not. 

 

When we run above example in swift playground we will get a result like as shown below

 

Both are Not Equal

This is how we can use equivalence operators in a swift programming language to check the equivalence in custom defined types based on our requirements.

Swift Custom Operator

In swift, we can declare and implement our own custom operators in addition to the standard operators provided by swift. 

 

We need to define new operators on the global level using operator keyword and those that need to mark with prefix, infix or postfix modifiers. 

 

Following is the example of implementing a new custom operator (+++) in a swift programming language.

 

prefix operator +++

struct Customop {

var x = 0.0, y = 0.0

}

extension Customop {

static prefix func +++ (left: inout Customop) -> Customop {

left += left

return left

}

}

var num1 = Customop(x: 4, y: 5)

var num2 = +++num1

print(num1)

print(num2)

If you observe above example we defined a custom operator (+++) in global level using operator keyword. After that we used a prefix modifier to implement custom functionality for custom operator (+++).

 

When we run above example in swift playground we will get a result like as shown below

 

(8.0, 10.0)

(8.0, 10.0)

This is how we can implement custom operators in a swift programming language based on our requirements.