Quick Answer
Structs are value types with automatic memberwise initializers
Understanding the Issue
Swift structs are preferred for simple data models. They get automatic initializers, are copied on assignment, and work well with SwiftUI. Use them when you don't need inheritance or reference semantics.
The Problem
This code demonstrates the issue:
Swift
Error
// Problem: Reference semantics with class
class Point {
var x, y: Int
init(x: Int, y: Int) { self.x = x; self.y = y }
}
let p1 = Point(x: 1, y: 2)
let p2 = p1
p2.x = 3 // p1.x also changes
The Solution
Here's the corrected code:
Swift
Fixed
// Solution: Value semantics with struct
struct Point {
var x, y: Int
}
let p1 = Point(x: 1, y: 2)
let p2 = p1
p2.x = 3 // p1.x unchanged
// Memberwise initializer comes free
let origin = Point(x: 0, y: 0)
Key Takeaways
Prefer structs for simple models unless you specifically need reference semantics.