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 is the bitwise AND assignment operator in Swift. It performs a bitwise AND operation between the binary representations of two integer operands and immediately assigns the resulting value to the left-hand operand. It serves as a syntactic shorthand, where a &= b is strictly equivalent to a = a & b.

Syntax

lhs &= rhs
  • lhs: A mutable variable (var) conforming to a bitwise protocol (typically BinaryInteger).
  • rhs: An expression of the exact same type as lhs.

Mechanics

The operator evaluates the operands bit by bit. For each corresponding position in the binary representation, the resulting bit is set to 1 if and only if both the lhs bit and the rhs bit are 1. Otherwise, the resulting bit is set to 0.
lhs bitrhs bitResulting lhs bit
111
100
010
000

Code Visualization

var a: UInt8 = 0b1100_1010 // Decimal: 202
let b: UInt8 = 0b1010_1111 // Decimal: 175

a &= b 

// Evaluation process:
//   11001010 (a)
// & 10101111 (b)
// -------
//   10001010 (Result assigned to a)

print(String(a, radix: 2)) // Prints: 10001010
print(a)                   // Prints: 138

Technical Constraints

  1. Type Strictness: Swift’s strong type system dictates that both operands must be of the exact same type. You cannot apply &= between a UInt8 and a UInt16 without explicit casting.
  2. Mutability: Because this is an assignment operator, the left-hand operand must be mutable. Attempting to use &= on a let constant will result in a compile-time error.
  3. Operator Overloading: The &= operator can be implemented for custom types. To do so, you define a static func &= (lhs: inout CustomType, rhs: CustomType) method within the type’s definition or extension. Types conforming to the BinaryInteger protocol receive this operator by default.
Master Swift with Deep Grasping Methodology!Learn More