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 ^ operator in Swift is the bitwise XOR (exclusive OR) operator. It performs a logical exclusive OR operation on the corresponding bits of two integer operands. The operator evaluates the binary representation of both values and returns a new integer where each bit is set to 1 if the corresponding bits of the operands differ, and 0 if they are identical.

Bitwise Evaluation Logic

For any given bit position, the ^ operator applies the following truth table:
  • 0 ^ 0 evaluates to 0
  • 0 ^ 1 evaluates to 1
  • 1 ^ 0 evaluates to 1
  • 1 ^ 1 evaluates to 0

Syntax and Execution

The operator requires both operands to be of the exact same type and must conform to the BinaryInteger protocol (e.g., Int, UInt8, Int32).
let lhs: UInt8 = 0b0011_1100  // Decimal 60
let rhs: UInt8 = 0b0000_1111  // Decimal 15

let result = lhs ^ rhs        // Evaluates to 0b0011_0011 (Decimal 51)

Compound Assignment (^=)

Swift provides the ^= compound assignment operator, which performs the bitwise XOR operation and assigns the result directly to the left-hand operand. The left-hand operand must be a mutable variable (var).
var bitPattern: UInt8 = 0b1010_1010
bitPattern ^= 0b1111_0000 

// bitPattern is mutated to 0b0101_1010

Technical Constraints and Characteristics

  • Type Safety: Swift enforces strict type safety. You cannot apply the ^ operator across mismatched integer types (e.g., Int8 and Int16) without explicit casting.
  • Floating-Point Rejection: The ^ operator cannot be applied to Float, Double, or CGFloat types. Bitwise operations in Swift are strictly reserved for integer bit patterns.
  • Operator Precedence: The ^ operator belongs to the AdditionPrecedence group. In Swift’s order of operations, it has lower precedence than the bitwise AND operator (&, which belongs to MultiplicationPrecedence), but shares the exact same precedence level as the bitwise OR operator (|), as well as standard addition (+) and subtraction (-). Because ^ and | share the same precedence group, they are evaluated left-to-right when chained together without parentheses.
Master Swift with Deep Grasping Methodology!Learn More