OOPMidOpen-ended

How do value types and reference types change the way you think about OOP in Swift?

Explanation & Code

Answer: Classic OOP assumes objects are reference types with identity and shared mutable state. Swift's struct/enum value types break that assumption: copies are independent, there's no shared mutable state to corrupt, and "object identity" doesn't apply. This pushes Swift OOP toward composition and protocols over inheritance, since value types can't be subclassed.

struct Point {            // value type — copied on assignment
    var x, y: Double
}
var a = Point(x: 0, y: 0)
var b = a
b.x = 10
// a.x is still 0 — independent copies, no aliasing bugs

class Counter {           // reference type — shared identity
    var count = 0
}
let c1 = Counter()
let c2 = c1
c2.count = 10
// c1.count is also 10 — same instance

Rule of thumb: reach for struct (value semantics, thread-safe copies, no inheritance) by default, and use class when you specifically need shared, mutable identity (e.g., view controllers, caches, observable state).

Rate your understanding:

Related Questions

Browse all OOP questions

Ready to practice more OOP?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.