Hint: updateValue returns old value wrapped in Optional or nil if new key [OK]
Common Mistakes:
Expecting updateValue to return new value
Forgetting Optional wrapping
Not updating dictionary correctly
4. Identify the error in this Swift code snippet:
var dict = ["a": 1, "b": 2]
let removed = dict.removeValue(forKey: "c")
print(removed!)
medium
A. Dictionary keys must be integers, not strings.
B. Force unwrapping removed causes runtime crash if key missing.
C. removeValue(forKey:) does not exist for dictionaries.
D. print statement syntax is incorrect.
Solution
Step 1: Understand removeValue return type
removeValue(forKey:) returns an Optional value. If key is missing, it returns nil.
Step 2: Analyze force unwrapping
Force unwrapping removed! when key "c" is missing causes a runtime crash.
Final Answer:
Force unwrapping removed causes runtime crash if key missing. -> Option B
Quick Check:
Force unwrap nil causes crash [OK]
Hint: Avoid force unwrapping optional from removeValue without check [OK]
Common Mistakes:
Assuming removeValue always returns a value
Ignoring optional unwrapping
Thinking removeValue removes all keys
5. You have a dictionary var inventory = ["apple": 3, "banana": 5]. Write code to safely add 2 to the count of "orange", even if it doesn't exist yet, using dictionary default values. What is the correct way?
hard
A. inventory["orange"] = inventory["orange"]! + 2
B. inventory["orange"] = inventory["orange"] ?? 0 + 2
C. inventory.updateValue(inventory["orange"]! + 2, forKey: "orange")
D. inventory["orange"] = inventory["orange", default: 0] + 2
Solution
Step 1: Understand safe addition with default
Using inventory["orange", default: 0] returns 0 if "orange" key is missing.
Step 2: Increment value safely
Adding 2 to this default value and assigning back to inventory["orange"] updates or creates the key safely.
Final Answer:
inventory["orange"] = inventory["orange", default: 0] + 2 -> Option D
Quick Check:
dict[key] = dict[key, default: 0] + value for safe increments [OK]
Hint: Use dict[key] = dict[key, default: 0] + amount to add safely [OK]
Common Mistakes:
Force unwrapping missing keys causing crash
Using += on read-only default subscript
Using updateValue without checking for nil
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.