Implicitly-Unwrapped Optional

ID

swift.implicitly_unwrapped_optional

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Swift

Tags

code-smell, optionals, reliability

Description

Reports a type declared as an implicitly-unwrapped optional (T!). The first time the value is read while it is nil, the program crashes with "unexpectedly found nil while unwrapping an Optional". The crash is silent at compile time and removes the safety net the optional type was meant to provide.

var name: String!                       // FLAW
func makeService() -> Service! { ... }  // FLAW
func consume(s: String!) { ... }        // FLAW

var name: String?                       // OK
@IBOutlet var label: UILabel!           // OK — IBOutlet exception

Rationale

T! was designed for a narrow case (objects wired by Interface Builder, two-phase initialization across class hierarchies). Using it elsewhere trades a compile-time guarantee for a runtime crash. The caller never sees the optional, so they cannot defensively handle nil even if they wanted to.

@IBOutlet properties are not flagged: Interface Builder wires them between init and viewDidLoad, and the IUO form is the idiomatic choice.

Remediation

Replace T! with T? and unwrap explicitly:

var name: String?

if let name = name {
  print(name)
}

guard let service = makeService() else { return }