Unused Local Variable
ID |
swift.unused_local_variable |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Dead Code |
Language |
Swift |
Tags |
CWE:563, dead-code, suspicious-code, unused-code |
Description
Reports a local var or let declaration whose name is never read
in its enclosing scope. Re-assigning the variable does not count as a
read, so a value that is written but never observed is still flagged.
func work() {
let x = 1 // FLAW — never read
let y = 2
print(y) // OK — `y` is read
var z = 3
z = 4 // write only, no read
// FLAW on `z`
}
Rationale
A local that is never read is dead code: removing it cannot change the
behaviour of the program, and keeping it around forces every reader to
prove that for themselves. Variables that are deliberately discarded
should be spelled with the wildcard _ (or a leading-underscore name)
so the intent is explicit.
The rule is conservative — it ignores cases where the binding has a documentary purpose even when unused:
-
for x in seq { … }— covered byfor_where/unused_index. -
if let x = …,guard let x = … else,while let x = …— the binding asserts the optional is non-nil. -
Pattern bindings such as
case .foo(let x).