Discouraged Optional Boolean

ID

swift.discouraged_optional_boolean

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Swift

Tags

code-smell, optionals

Description

Reports any explicit Bool?, Bool! or Optional<Bool> type annotation. A three-state boolean (true / false / nil) is almost always a code smell: callers must now handle every state and the intent of nil is rarely clear from the call site.

var enabled: Bool?              // FLAW
func check() -> Bool? { ... }   // FLAW
func f(x: Bool?) { ... }        // FLAW

var enabled: Bool = false       // OK
func check() -> Bool { ... }    // OK
var count: Int? = nil           // OK — non-Bool optional is fine

Rationale

A Bool? collapses three concepts (true, false, unknown) into a single type without naming them. Callers tend to forget to handle nil, or treat it as either true or false inconsistently. A plain Bool with a sensible default, or an explicit enum for the unknown state, makes the intent unambiguous.

Remediation

Replace the optional boolean with a plain Bool (with a default) or a domain-specific enum:

var enabled: Bool = false

enum Tristate { case yes, no, unknown }
var enabled: Tristate = .unknown