Bird
0
0

What is the correct way?

hard📝 Application Q15 of 15
Swift - Collections
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?
Ainventory["orange"] = inventory["orange"]! + 2
Binventory["orange"] = inventory["orange"] ?? 0 + 2
Cinventory.updateValue(inventory["orange"]! + 2, forKey: "orange")
Dinventory["orange"] = inventory["orange", default: 0] + 2
Step-by-Step Solution
Solution:
  1. Step 1: Understand safe addition with default

    Using inventory["orange", default: 0] returns 0 if "orange" key is missing.
  2. Step 2: Increment value safely

    Adding 2 to this default value and assigning back to inventory["orange"] updates or creates the key safely.
  3. Final Answer:

    inventory["orange"] = inventory["orange", default: 0] + 2 -> Option D
  4. Quick Check:

    dict[key] = dict[key, default: 0] + value for safe increments [OK]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes