Bird
0
0

Given var fruits = ["apple": 4, "banana": 6], how can you safely add 1 to the count of "pear", initializing it if it doesn't exist?

hard📝 Application Q8 of 15
Swift - Collections
Given var fruits = ["apple": 4, "banana": 6], how can you safely add 1 to the count of "pear", initializing it if it doesn't exist?
Afruits.updateValue(fruits["pear"]! + 1, forKey: "pear")
Bfruits["pear", default: 0] += 1
Cfruits["pear"] = fruits["pear"]! + 1
Dfruits["pear"] = fruits["pear"] ?? 1
Step-by-Step Solution
Solution:
  1. Step 1: Use dictionary subscripting with default

    To safely increment a value for a key that might not exist, use fruits["pear", default: 0] which returns 0 if "pear" is missing.
  2. Step 2: Increment the value

    Adding 1 to this defaulted value updates the dictionary correctly.
  3. Step 3: Analyze other options

    fruits.updateValue(fruits["pear"]! + 1, forKey: "pear") and C force unwrap optional values which can cause runtime errors if the key is missing. fruits["pear"] = fruits["pear"] ?? 1 sets the value to 1 if missing but does not increment existing values.
  4. Final Answer:

    fruits["pear", default: 0] += 1 -> Option B
  5. Quick Check:

    Check safe increment with default subscript [OK]
Quick Trick: Use dict[key, default: 0] += 1 to safely increment [OK]
Common Mistakes:
  • Force unwrapping optional values without checking
  • Not handling missing keys before incrementing
  • Assigning default value instead of incrementing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes