What is bit manipulation?

Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word. Computer programming tasks that require bit manipulation include low-level device control, error detection and correction algorithms, data compression, encryption algorithms, and optimization.

- Wikipedia

bitwise NOT operator

the bitwise NOT operator (~) inverts all bits in a number.

bitwise NOT diagram

The NOT operator basically helps you find the “opposite” value by inverting all the bits

let initialBitsUInt8: UInt8 = 0b00001111 // 00001111 = 15
let invertedBitsUInt8: UInt8 = ~initialBitsUInt8 // 11110000 = 240

let initialBitsUInt16: UInt16 = 0b00001111 // 00000000 00001111 = 15
let invertedBitsUInt16: UInt16 = ~initialBitsUInt16 // 11111111 11110000 = 65520

let initialBitsUInt32: UInt32 = 0b00001111 // 00000000 00000000 00001111 = 15
let invertedBitsUInt32: UInt32 = ~initialBitsUInt32 // 11111111 11111111 11110000 = 4294967280

bitwise AND operator

the bitwise AND operator (&) combines the bits of two numbers and returns a new number whose bits are set to 1 only if the bits were equal to 1 in both input numbers

bitwise AND diagram

bitwise OR operator

the bitwise OR operator ( ) compares the bits of two numbers. The operator returns a new number whose bits are set to 1 if the bits are equal to 1 in either input number.

bitwise OR diagram

bitwise XOR operator

the bitwise XOR operator , or “exclusive OR operator” (^), compares the bits of two numbers. The operator returns a new number whose bits are set to 1 where the input bits are different and are set to 0 where the input bits are the same.

bitwise XOR diagram

Reference

The Swift Programming Language