ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Swift Tutorial• 7 min read

Structures vs Classes: Value vs Reference Types

Why Swift favors structs: Copy-on-Write, mutability, and ARC reference counting

Choosing between struct (Value Type) and class (Reference Type) is a fundamental architectural decision in Swift. Apple strongly recommends structs for almost all models.

Value Types (Struct) vs Reference Types (Class)

Structs (Value Types): Passed by copy. Modifying a copy does not affect the original instance. Free memberwise initializers. Thread-safe by design!

Classes (Reference Types): Passed by reference. Multiple variables point to the same memory instance on the heap. Support inheritance and deinitializers (deinit).

Copy-on-Write: Swift optimizes value types so memory is only duplicated when a copy is actually modified.

Value Type Independence Demonstration
struct Point {
    var x: Int
    var y: Int
}

var p1 = Point(x: 10, y: 20)
var p2 = p1 // p2 is an independent copy!

p2.x = 99

print("p1.x is still:", p1.x) // 10 (Completely unaffected!)
print("p2.x is:", p2.x)       // 99
Struct copies are completely isolated, eliminating shared mutable state bugs.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What happens when you assign an instance of a `struct` to a new variable in Swift?