Boolean Return Nil
ID |
swift.boolean_return_nil |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Swift |
Tags |
code-smell, optionals |
Description
Reports a return nil statement inside a function whose declared
return type is Bool? (or Optional<Bool>). The caller is now forced
to distinguish three states — true, false, nil — and cannot tell
which case the implementation meant by returning nil.
func isReady() -> Bool? {
if Bool.random() { return true }
return nil // FLAW
}
func isReady() -> Bool { return Bool.random() } // OK
func findId() -> Int? { return nil } // OK — non-Bool optional
Rationale
A Bool already encodes exactly two states. Promoting it to Bool? and
returning nil collapses an extra "unknown" state into the same type
without naming it. Callers tend to forget the nil branch, or write
x ?? false and silently lose information.
Remediation
Pick one of:
-
Return a plain
Booland pick a default for the unknown case. -
Throw an error to signal "I cannot decide".
-
Model the unknown state explicitly with an enum.
enum Readiness { case yes, no, unknown }
func isReady() -> Readiness { ... }
func isReady() throws -> Bool { ... }