Bird
0
0

Find the mistake in this code snippet:

medium📝 Debug Q7 of 15
Swift - Collections
Find the mistake in this code snippet:
var dict = ["x": 10]
var copy = dict
copy["y"] = 20
print(dict["y"]!)
AMissing type annotation for dictionary
BDictionaries cannot be copied in Swift
CAccessing a key that does not exist causes a runtime error
DCannot assign new keys to copied dictionary
Step-by-Step Solution
Solution:
  1. Step 1: Understand dictionary copy behavior

    Copying creates a new dictionary; adding "y" to copy does not add it to original.
  2. Step 2: Check print statement

    Accessing dict["y"] fails because "y" is not a key in original dict, causing runtime error.
  3. Final Answer:

    Accessing a key that does not exist causes a runtime error -> Option C
  4. Quick Check:

    Accessing missing keys causes error [OK]
Quick Trick: Check keys exist before force unwrapping dictionary values [OK]
Common Mistakes:
  • Assuming copied dictionary shares keys
  • Forgetting to safely unwrap optional values
  • Expecting compile error instead of runtime error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes