Bird
0
0

Identify the error in this Swift code related to collections as value types:

medium📝 Debug Q14 of 15
Swift - Collections
Identify the error in this Swift code related to collections as value types:
var list1 = ["a", "b"]
var list2 = list1
list2.append("c")
print(list1)
ANo error; output is ["a", "b"]
BAppending to list2 causes a compile error
Clist1 changes unexpectedly after modifying list2
Dlist1 and list2 share the same reference
Step-by-Step Solution
Solution:
  1. Step 1: Analyze value type behavior in code

    list2 is a copy of list1; modifying list2 does not affect list1.
  2. Step 2: Check output of print(list1)

    list1 remains ["a", "b"] because collections are value types.
  3. Final Answer:

    No error; output is ["a", "b"] -> Option A
  4. Quick Check:

    Value types keep original unchanged [OK]
Quick Trick: Modifying copy doesn't affect original collection [OK]
Common Mistakes:
  • Thinking list1 changes after list2 append
  • Expecting a compile or runtime error
  • Believing collections are reference types by default

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes