Bird
0
0

What is the output of this Swift code?

medium📝 Predict Output Q4 of 15
Swift - Collections
What is the output of this Swift code?
var dict = ["a": 1, "b": 2]
dict["c", default: 0] += 3
print(dict)
A["a": 1, "b": 2, "c": 3]
B["a": 1, "b": 2]
C["a": 1, "b": 2, "c": 0]
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand default subscript usage

    dict["c", default: 0] returns 0 if "c" is missing, then adds 3 and assigns back.
  2. Step 2: Check dictionary after operation

    Since "c" was missing, it is added with value 3.
  3. Final Answer:

    ["a": 1, "b": 2, "c": 3] -> Option A
  4. Quick Check:

    Default subscript adds missing key with updated value [OK]
Quick Trick: Default subscript adds missing keys when mutated [OK]
Common Mistakes:
  • Expecting no change to dictionary
  • Thinking default value is not assigned back
  • Assuming runtime error due to mutation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes