Dead Stores

ID

swift.dead_stores

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Swift

Tags

CWE:563, dead-code, reliability, suspicious-code

Description

Reports a write to a local variable whose stored value is never read before being overwritten or before the enclosing scope exits. A dead store is wasted work and almost always a sign of a copy-paste mistake, a stale debug edit, or an accidental name shadow.

func compute() -> Int {
    var x = 0
    x = 1                  // FLAW — overwritten on the next line
    x = 2
    return x
}

func fallOff() {
    var x = 0
    x = 1                  // FLAW — block ends with no read
}

Rationale

The compiler does not emit a warning for ordinary dead local writes, so they survive into release builds. Even when the wasted assignment is cheap, the pattern usually hides a bug — the author meant the value to be read but the read got lost in a later refactor.

Remediation

Remove the dead assignment, or replace it with the one the author actually meant:

// 1) drop the dead write
func compute() -> Int {
    var x = 0
    x = 2
    return x
}

// 2) read the value before overwriting it
func compute() -> Int {
    var x = 0
    x = 1
    print(x)
    x = 2
    return x
}

When not to fire

The rule is intentionally conservative and skips:

  • compound assignments (+=, -=, …​) — those read the current value as part of the operation;

  • subscript writes (arr[0] = 1) and member writes (self.x = …​) — those mutate a structured target whose alias-analysis is out of reach;

  • writes followed by any compound statement (if, for, while, do-catch, switch, guard, …​) — the rule analyzes only straight-line sequences of expression statements;

  • writes whose RHS reads the same variable (x = x + 1).