Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid duplicate key error in swift when iterating over a dictionary

I'm practicing swift and I'm trying to iterate over a Dictionary to print the key, but it gives me a

fatal error: Dictionary literal contains duplicate keys

How can remove the error?

let people = ["age":14, "age":15, "age":75, "age":43, "age":103, "age":87, "age":12]
for (key, value) in people {
    print(value)
}
like image 577
edmamerto Avatar asked Jan 02 '16 18:01

edmamerto


People also ask

Can dictionaries have duplicate keys Swift?

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.

How do dictionary handle duplicate keys?

If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary. The dictionary can not have the same keys, but we can achieve a similar effect by keeping multiple values for a key in the dictionary.

Does dictionary accept duplicate keys?

[C#] Dictionary with duplicate keys The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .

Can a dictionary have multiple identical keys?

No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.


1 Answers

Each dictionary key MUST be unique

let people = ["age1":14, "age2":15, "age3":75, "age4":43, "age5":103, "age6":87, "age7":12]
for (key, value) in people {
    print(value)
}
like image 124
nsinvocation Avatar answered Oct 19 '22 10:10

nsinvocation