Redundant Optional Initialization

ID

swift.redundant_optional_initialization

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Swift

Tags

code-smell, style

Description

Reports a var whose annotated type is optional (T?) and whose initializer is literally nil. The explicit = nil is redundant — an uninitialised optional already defaults to nil.

var a: Int? = nil      // FLAW
var b: String? = nil   // FLAW

var a: Int?            // OK
var b: Int? = 5        // OK
let c: Int? = nil      // OK — let requires an initializer

Rationale

Writing = nil on every optional is noisy and suggests the author was unaware of the language’s default. Removing it makes the declaration’s intent clearer.

Remediation

Drop the = nil:

var a: Int?
var b: String?