Bird
0
0

Consider the following Swift code:

medium📝 Predict Output Q13 of 15
iOS Swift - Swift Language Essentials
Consider the following Swift code:
struct Point {
  var x: Int
  var y: Int
}

var p1 = Point(x: 1, y: 2)
var p2 = p1
p2.x = 5
print(p1.x)

What will be printed?
A1
B5
C0
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand struct copying behavior

    Since Point is a struct (value type), assigning p1 to p2 copies the data. They are independent.
  2. Step 2: Analyze mutation and print

    Changing p2.x to 5 does not affect p1.x. So p1.x remains 1. The print statement outputs 1.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    Structs copy on assignment, so original stays unchanged [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 on mutation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes