Bird
0
0

What is the output of this Swift code?

medium📝 Predict Output Q13 of 15
Swift - Collections
What is the output of this Swift code?
var scores = ["Alice": 10, "Bob": 8]
let oldValue = scores.updateValue(12, forKey: "Alice")
let missingValue = scores.updateValue(5, forKey: "Charlie")
print(oldValue, missingValue, scores)
Anil Optional(5) ["Alice": 12, "Bob": 8, "Charlie": 5]
B10 5 ["Alice": 12, "Bob": 8, "Charlie": 5]
COptional(10) nil ["Alice": 12, "Bob": 8, "Charlie": 5]
DOptional(12) Optional(5) ["Alice": 10, "Bob": 8, "Charlie": 5]
Step-by-Step Solution
Solution:
  1. Step 1: Understand updateValue return values

    Updating "Alice" from 10 to 12 returns old value Optional(10). Adding "Charlie" returns nil because key was missing.
  2. Step 2: Check dictionary after updates

    Dictionary now has "Alice":12, "Bob":8, and "Charlie":5.
  3. Final Answer:

    Optional(10) nil ["Alice": 12, "Bob": 8, "Charlie": 5] -> Option C
  4. Quick Check:

    updateValue returns old value or nil [OK]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes