Redundant Optional Initialization

Initializing an optional variable with nil is redundant

  • Identifier: redundant_optional_initialization
  • Enabled by default: Yes
  • Supports autocorrection: Yes
  • Kind: idiomatic
  • Analyzer rule: No
  • Minimum Swift compiler version: 5.0.0
  • Default configuration:
    KeyValue
    severity warning

Non Triggering Examples

var myVar: Int?
let myVar: Int? = nil
var myVar: Int? = 0
func foo(bar: Int? = 0) { }
var myVar: Optional<Int>
let myVar: Optional<Int> = nil
var myVar: Optional<Int> = 0
var foo: Int? {
  if bar != nil { }
  return 0
}
var foo: Int? = {
  if bar != nil { }
  return 0
}()
lazy var test: Int? = nil
func funcName() {
  var myVar: String?
}
func funcName() {
  let myVar: String? = nil
}

Triggering Examples

var myVar: Int? = nil
var myVar: Optional<Int> = nil
var myVar: Int?=nil
var myVar: Optional<Int>=nil
)
var myVar: String? = nil {
  didSet { print("didSet") }
}
func funcName() {
    var myVar: String? = nil
}