Duplicate Enum Cases
ID |
swift.duplicate_enum_cases |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Swift |
Tags |
enum, reliability |
Description
Reports two or more enum cases in the same declaration that share the
same raw value. Swift’s compiler emits only a warning, but
EnumType(rawValue: x) silently returns one of the conflicting cases —
almost always a bug.
enum Status: Int {
case active = 1 // FLAW
case inactive = 1 // FLAW
case pending = 2 // OK
}
enum Color: String {
case red = "red" // FLAW
case crimson = "red" // FLAW
case blue = "blue" // OK
}
Rationale
The compiler warning is easy to miss in a large project, and the runtime
behaviour of init(rawValue:) is unspecified for conflicting raw
values. Two cases that should be distinct become indistinguishable at
serialization boundaries (JSON decoding, persistence, IPC).
Remediation
Pick distinct raw values, or rethink the model:
enum Status: Int {
case active = 1
case inactive = 2
case pending = 3
}
// If two names really should map to the same value, use a static constant
// rather than a duplicate case.
enum Color: String {
case red = "red"
case blue = "blue"
static let crimson = Color.red
}