Created
March 11, 2021 05:44
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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