Bird
0
0

What happens if you create a Swift dictionary with duplicate keys in the literal?

hard📝 Conceptual Q10 of 15
Swift - Collections
What happens if you create a Swift dictionary with duplicate keys in the literal?
let dict = ["x": 1, "y": 2, "x": 3]
ACompiler error due to duplicate keys
BRuntime error when accessing duplicate keys
CThe first value for the duplicate key is used
DThe last value for the duplicate key is used
Step-by-Step Solution
Solution:
  1. Step 1: Understand dictionary literal behavior

    Swift allows duplicate keys in literals but keeps the last value assigned to that key.
  2. Step 2: Check for errors

    No compile or runtime error occurs; the dictionary stores the last value for "x".
  3. Final Answer:

    The last value for the duplicate key is used -> Option D
  4. Quick Check:

    Duplicate keys keep last value in Swift dictionary [OK]
Quick Trick: Duplicate keys keep last value in dictionary literal [OK]
Common Mistakes:
  • Expecting compiler error
  • Thinking first value is kept
  • Assuming runtime error occurs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes