Duplicated Dictionary Key

ID

swift.duplicated_dict_key

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Swift

Tags

collection, reliability

Description

Reports duplicate keys in a dictionary literal. Swift silently keeps the last value, so the other pairs are dropped — almost always a typo or copy / paste bug.

let scores: [String: Int] = [
    "alice": 10,                          // FLAW
    "bob":   20,
    "alice": 30                           // FLAW — silently overrides "alice": 10
]

Rationale

The Swift compiler does not emit a diagnostic for duplicate keys; the runtime simply keeps the last assignment in source order. The dropped entries become invisible defects: lookups silently return wrong values, or callers see fewer entries than the literal seems to declare.

Remediation

Remove duplicates, or build the dictionary explicitly so the deduplication is intentional:

let scores: [String: Int] = [
    "alice": 30,
    "bob":   20
]

// If you need merging behaviour, use Dictionary(_:uniquingKeysWith:):
let pairs = [("alice", 10), ("bob", 20), ("alice", 30)]
let scores = Dictionary(pairs, uniquingKeysWith: max)