Bird
0
0

What will be printed by this Swift code?

medium📝 Predict Output Q4 of 15
iOS Swift - Swift Language Essentials
What will be printed by this Swift code?
struct Point {
  var x: Int
  var y: Int
}

var p1 = Point(x: 1, y: 2)
var p2 = p1
p2.x = 10
print(p1.x)
A10
BCompilation error
C0
D1
Step-by-Step Solution
Solution:
  1. Step 1: Understand struct assignment behavior

    Structs are value types, so p2 is a copy of p1.
  2. Step 2: Analyze mutation effect

    Changing p2.x does not affect p1.x, so p1.x remains 1.
  3. Final Answer:

    1 -> Option D
  4. Quick Check:

    Struct copy means original unchanged = B [OK]
Quick Trick: Structs copy on assignment; changes don't affect original [OK]
Common Mistakes:
  • Assuming p1.x changes when p2.x changes
  • Confusing structs with classes (reference types)
  • Expecting runtime error due to mutation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes