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 -= (subtraction assignment) operator is a compound assignment operator that subtracts the value of the right-hand operand from the left-hand operand, immediately assigning the computed difference back to the left-hand operand.
lhs -= rhs
This operation is semantically equivalent to the expanded assignment:
lhs = lhs - rhs

Technical Mechanics

  • Mutability: The left-hand operand (lhs) must be a mutable variable (declared with var). It cannot be a constant (let) or a read-only computed property.
  • Type Constraints and Overloading: While standard numeric types implement this operator via the AdditiveArithmetic protocol (requiring both operands to resolve to the same type), Swift’s operator overloading permits differing types. For instance, types conforming to the Strideable protocol implement -= where the left-hand operand is Self and the right-hand operand is Self.Stride (e.g., subtracting an Int from an UnsafeMutablePointer).
  • Underlying Signature: At the compiler level, the operator is implemented as a static method. The left-hand operand is passed as an inout parameter, allowing the function to mutate the original variable directly in memory. Depending on the protocol conformance, the signature varies:
// AdditiveArithmetic implementation
static func -= (lhs: inout Self, rhs: Self)

// Strideable implementation
static func -= (lhs: inout Self, rhs: Self.Stride)
  • Evaluation Guarantee: Unlike the expanded lhs = lhs - rhs syntax, the compound -= operator guarantees that the left-hand operand is evaluated exactly once. This provides a performance optimization and prevents unintended side effects when lhs involves complex subscripting or computed property access.
  • Overflow Safety: Swift enforces strict memory safety. If the subtraction operation results in a value that falls below the minimum representable bounds of an integer type (underflow), the -= operator will trigger a runtime trap and crash the application. To perform two’s-complement wrapping subtraction without trapping, Swift natively provides the compound overflow subtraction assignment operator:
lhs &-= rhs
Master Swift with Deep Grasping Methodology!Learn More