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

# Swift Unary Minus

An operator in Swift is a specialized lexical token—typically a symbol or a short phrase—that performs mathematical, relational, logical, or bitwise operations on one or more operands. Swift operators are strictly typed, enforce memory safety by trapping on overflow by default, and support custom definitions with explicit precedence and associativity.

## Classification by Arity and Fixity

Operators are categorized by the number of operands they accept (arity) and their position relative to those operands (fixity).

* **Unary Operators:** Operate on a single operand.
  * **Prefix:** Placed immediately before the operand without whitespace.
  ```swift theme={"dark"}
  ```

let b = 5
let a = -b

let d = true
let c = !d

````
    *   **Postfix:** Placed immediately after the operand without whitespace.
    ```swift
let f: Int? = 10
let e = f!
````

* **Binary Operators:** Operate on two operands. They are always **infix**, placed between the two operands. Swift requires consistent whitespace on both sides of a binary operator to resolve ambiguity.

```swift theme={"dark"}
let h = 3
let i = 4
let g = h + i
```

* **Ternary Operators:** Operate on three operands. Swift implements a single ternary conditional operator.

```swift theme={"dark"}
let condition = true
let trueValue = 10
let falseValue = 20
let j = condition ? trueValue : falseValue
```

## Core Operator Categories

**Assignment Operator**
The assignment operator (`=`) initializes or mutates a value. Unlike in C or Objective-C, the assignment operator in Swift does not return a value. This design prevents accidental assignment within conditional statements.

```swift theme={"dark"}
var x = 5
let y = 10
x = y
```

**Arithmetic Operators**
Standard arithmetic operators (`+`, `-`, `*`, `/`, `%`) perform mathematical operations. Swift prevents silent arithmetic overflow; operations that exceed the bounds of the type will trigger a runtime trap.

```swift theme={"dark"}
let sum = 5 + 3
let remainder = 10 % 3
```

*Note: To explicitly permit overflow, Swift provides specialized overflow operators (`&+`, `&-`, `&*`).*

**Comparison and Identity Operators**
Comparison operators evaluate to a `Bool`. Identity operators (`===`, `!==`) check whether two object references point to the exact same instance in memory, which is distinct from value equality (`==`).

```swift theme={"dark"}
let val1 = 5
let val2 = 5
let isEqual = val1 == val2 // Value equality

class ReferenceType {}
let ref1 = ReferenceType()
let ref2 = ref1
let isIdentical = ref1 === ref2 // Reference identity
```

**Nil-Coalescing Operator**
The nil-coalescing operator (`??`) unwraps an optional type if it contains a value, or falls back to a default value if the optional is `nil`. It utilizes short-circuit evaluation; the right-hand operand is not evaluated if the left-hand operand is non-nil.

```swift theme={"dark"}
let optionalValue: String? = nil
let fallbackValue = "Default String"
let result = optionalValue ?? fallbackValue
```

**Range Operators**
Swift provides specialized operators to construct `Range` and `ClosedRange` types.

* **Closed Range (`...`):** Defines a range running from the lower bound to the upper bound, inclusive.
* **Half-Open Range (`..<`):** Defines a range running from the lower bound to the upper bound, exclusive of the upper bound.
* **One-Sided Range:** Omits either the lower or upper bound to create a partial range.

```swift theme={"dark"}
let start = 1
let end = 5
let closed = start...end
let halfOpen = start..<end
let oneSided = start...
```

**Logical and Bitwise Operators**

* **Logical:** (`!`, `&&`, `||`) Operate on boolean logic. The `&&` and `||` operators employ short-circuit evaluation.
* **Bitwise:** (`~`, `&`, `|`, `^`, `<<`, `>>`) Manipulate the raw data bits within a data structure.

## Precedence and Associativity

Infix operators are governed by precedence and associativity rules, which dictate the parsing order of complex expressions without explicit parentheses.

* **Precedence:** Determines which operator binds tighter to its operands (e.g., multiplication has higher precedence than addition).
* **Associativity:** Determines how operators of the exact same precedence are grouped (left-associative or right-associative).

## Custom Operators

Swift allows the declaration of custom operators using the `operator` keyword. Custom operators must be declared at the global scope and assigned a fixity (`prefix`, `infix`, or `postfix`).

Infix operators can optionally be assigned to a `precedencegroup` to define their evaluation order relative to other operators. If a precedence group is not explicitly specified, Swift automatically assigns the custom infix operator to a default precedence group (`DefaultPrecedence`), which has a precedence immediately higher than the ternary conditional operator.

```swift theme={"dark"}
import Foundation

prefix operator +++
infix operator ** : MultiplicationPrecedence

extension Int {
    static prefix func +++ (vector: inout Int) {
        vector += 2
    }
    
    static func ** (left: Int, right: Int) -> Int {
        return Int(pow(Double(left), Double(right)))
    }
}

var myVector = 3
+++myVector // Mutates myVector to 5

let powerResult = 2 ** 3 // Evaluates to 8
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Swift Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
