Skip to content

Instantly share code, notes, and snippets.

@kewlbear
Created March 11, 2021 05:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kewlbear/ed29cd01e8c9b293a372a450cf030481 to your computer and use it in GitHub Desktop.
Save kewlbear/ed29cd01e8c9b293a372a450cf030481 to your computer and use it in GitHub Desktop.
Swift currently crashes at runtime with "Fatal error: "Dictionary literal contains duplicate keys" if you have duplicate keys in a dictionary literal. They even don't print actual duplicate keys. This struct collects all the duplicate keys and print them with count.
struct DuplicateKeyChecker<Key: Hashable, Value>: ExpressibleByDictionaryLiteral {
init(dictionaryLiteral elements: (Key, Value)...) {
var count: [Key: Int] = [:]
for (key, _) in elements {
count[key] = (count[key] ?? 0) + 1
}
print(#function, "duplicate keys:", count.filter { $0.value > 1 })
}
}
// usage: specify the type of variable as DuplicateKeyChecker
let test: DuplicateKeyChecker = ["foo": 1, "bar": 2, "foo": 3,]
// prints this
init(dictionaryLiteral:) duplicate keys: ["foo": 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment