Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The ~ (bitwise NOT) operator is a unary prefix operator that inverts all bits in the binary representation of an integer. It performs a logical negation on each individual bit, transitioning every 0 to a 1 and every 1 to a 0 across the exact memory footprint of the underlying data type.

Syntax

As a prefix operator, ~ must be placed immediately before its operand without any intervening whitespace.
let invertedValue = ~originalValue

Bit-Level Mechanics

When applied to an unsigned integer, the operator performs a straightforward bitwise inversion bounded by the bit-width of the type.
let initialBits: UInt8 = 0b00001111 // Decimal: 15
let invertedBits = ~initialBits     // 0b11110000 (Decimal: 240)

Behavior with Signed Integers

Swift represents signed integers using two’s complement. Because the sign bit is also inverted by the ~ operator, applying it to a signed integer alters its sign and magnitude. Mathematically, applying the bitwise NOT operator to a signed integer x yields -(x + 1).
let signedInt: Int8 = 5         // Binary: 0b00000101
let invertedSigned = ~signedInt // Binary: 0b11111010 (Decimal: -6)

Operator Characteristics

  • Fixity: Prefix.
  • Type Constraints: The operand must conform to the BinaryInteger protocol.
  • Precedence: It evaluates with the highest precedence among bitwise operators. In an expression combining ~ with binary bitwise operators (like &, |, or ^), the ~ operation is resolved first.
let a: UInt8 = 0b00001111
let b: UInt8 = 0b11110000

// ~a is evaluated first, resulting in 0b11110000
// Then 0b11110000 & 0b11110000 is evaluated
let result = ~a & b // 0b11110000
Master Swift with Deep Grasping Methodology!Learn More