Swift

Swift

Made by DeepSource

Duplicate key in dictionary is likely a mistake SW-E1000

Bug risk
Critical

This issue occurs when there are duplicate keys in a Swift dictionary. A dictionary is a collection data type that stores key-value pairs. Each key in a dictionary is unique, and it maps to a single value. When a dictionary contains duplicate keys, it leads to confusing and error-prone behavior.

Duplicate keys in a dictionary can occur when initializing the dictionary with more than one entry for the same key. This can be a typographical mistake or a misunderstanding of how dictionaries work. An attempt to retrieve the value for the key may return an unexpected result, or the code may crash altogether.

To fix this issue, review the code and ensure that each key in the dictionary is unique. If there is a need to store multiple values for a key, consider using an array or a set as the dictionary value.

Bad Practice

let myDictionary = [
  "key1": "value1",
  "key2": "value2",
  "key1": "value3" // Duplicate key
]

Recommended

let myDictionary = [
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
]