Consider the following Swift code. What will be printed?
struct Point { var x: Int var y: Int } class Location { var x: Int var y: Int init(x: Int, y: Int) { self.x = x self.y = y } } var p1 = Point(x: 1, y: 1) var p2 = p1 p2.x = 5 var l1 = Location(x: 1, y: 1) var l2 = l1 l2.x = 5 print("p1.x = \(p1.x), p2.x = \(p2.x)") print("l1.x = \(l1.x), l2.x = \(l2.x)")
Remember that structs are value types and classes are reference types in Swift.
Structs are copied when assigned, so changing p2.x does not affect p1.x. Classes share references, so changing l2.x also changes l1.x.
You want to model a simple data type that represents a color with red, green, and blue values. You do not need inheritance or shared mutable state. Which is the best choice?
Think about whether you want copies or shared references.
Structs are ideal for simple data containers without inheritance. They are copied on assignment, which avoids unintended side effects.
Look at this Swift code snippet. Why does modifying person2 also change person1?
class Person { var name: String init(name: String) { self.name = name } } var person1 = Person(name: "Alice") var person2 = person1 person2.name = "Bob" print(person1.name) print(person2.name)
Think about how classes and structs behave differently when assigned.
Classes use reference semantics, so both variables refer to the same instance. Changing one changes the other.
Which option correctly fixes the syntax error in this Swift struct method that modifies a property?
struct Counter { var count = 0 func increment() { count += 1 } }
Struct methods that change properties must be marked specially.
In Swift, methods that modify properties of a struct must be marked with mutating to allow changes.
You are designing a Swift app with a model representing a user profile that can be shared and updated across multiple views. The profile has mutable properties and needs identity tracking. Which is the best choice?
Consider if you need shared mutable state and identity.
Classes are better when you need shared mutable state and identity, as they use reference semantics. Structs are copied and do not track identity.