Parameter Shadows Property

ID

swift.parameter_shadows_property

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Swift

Tags

naming, reliability

Description

Reports a method parameter whose internal name matches a stored property of the enclosing type. Inside the method body, the bare identifier resolves to the parameter and the property can only be reached through self., which is a common source of bugs.

class Account {
    var balance: Double = 0

    func deposit(balance: Double) {           // FLAW — `balance` shadows the property
        balance += 1                          // updates the parameter copy, not the field
    }

    func deposit(amount: Double) {            // OK
        balance += amount
    }
}

Rationale

Swift does not warn on a parameter that shadows a property; the bare identifier in the function body silently rebinds to the parameter, so an assignment that reads "looks like" it mutates the field actually only mutates a local copy. Reviewers and callers alike have to track which spelling refers to which binding. Renaming either the parameter or the property removes the ambiguity.

The rule only checks stored properties (the ones listed as variableDeclarators().isTypeProperty()). Computed and observed properties cannot be re-bound from a parameter, so the shadowing there is harmless.

Remediation

Rename the parameter so it cannot be confused with the property:

class Account {
    var balance: Double = 0
    func deposit(amount: Double) {
        balance += amount
    }
}

Or, if the parameter is intentionally the "new" value, mark the intent explicitly with self.:

class Account {
    var balance: Double = 0
    func setBalance(_ balance: Double) {
        self.balance = balance
    }
}