0
0
Swiftprogramming~3 mins

Why Classes are reference types in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if changing one thing could instantly update it everywhere without extra work?

The Scenario

Imagine you have a list of friends' contact cards written on paper. You want to share one card with a friend, but instead of giving them the original, you make a photocopy. Now, if you update the original card, your friend's copy doesn't change. This can get confusing if you want everyone to see the latest info.

The Problem

Manually copying data means you have many versions floating around. If you forget to update all copies, some friends have old info. This is slow and error-prone because you must track every copy and update it separately.

The Solution

Classes as reference types mean you share the same card, not copies. When you pass a class instance, everyone points to the same data. So, if one person updates the card, everyone sees the change instantly without extra work.

Before vs After
Before
struct ContactCard {
  var name: String
}
var friend1 = ContactCard(name: "Alice")
var friend2 = friend1 // copies data
friend2.name = "Bob"
print(friend1.name) // prints "Alice"
After
class ContactCard {
  var name: String
  init(name: String) { self.name = name }
}
var friend1 = ContactCard(name: "Alice")
var friend2 = friend1 // references same object
friend2.name = "Bob"
print(friend1.name) // prints "Bob"
What It Enables

This lets multiple parts of your program share and update the same data easily, keeping everything in sync without extra copying.

Real Life Example

Think of a multiplayer game where players share the same character object. If one player changes the character's outfit, all players see the update immediately because they reference the same character instance.

Key Takeaways

Copying data manually creates many versions that can get out of sync.

Classes as reference types let you share one object among many variables.

Updating one reference updates all, making data management simpler and safer.