Skip to main content
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.

Bit-Level Mechanics

When applied to an unsigned integer, the operator performs a straightforward bitwise inversion bounded by the bit-width of the type.

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).

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.
Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More