Bird
0
0

Identify the error in this Swift code related to string value type behavior:

medium📝 Debug Q14 of 15
Swift - Data Types
Identify the error in this Swift code related to string value type behavior:
var text1 = "Swift"
var text2 = text1
text2 += " Rocks"
print(text1)
Atext1 will print "Swift Rocks" because strings are reference types.
Btext1 will print "Swift" because strings are value types and text2 is a copy.
CThe code will cause a compile-time error due to append on text2.
Dtext1 will be empty because text2 overwrites it.
Step-by-Step Solution
Solution:
  1. Step 1: Understand string copying behavior

    Assigning text1 to text2 copies the string value.
  2. Step 2: Effect of appending to copied string

    Appending " Rocks" to text2 does not affect text1, which remains "Swift".
  3. Final Answer:

    text1 will print "Swift" because strings are value types and text2 is a copy. -> Option B
  4. Quick Check:

    Appending copy doesn't change original string [OK]
Quick Trick: Appending copy string doesn't affect original string [OK]
Common Mistakes:
  • Thinking append changes original string
  • Expecting reference type behavior for strings
  • Confusing append method usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes