0
0
Swiftprogramming~3 mins

Why classes exist alongside structs in Swift - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if you could update one thing and see the change everywhere instantly?

The Scenario

Imagine you want to organize information about many people, like their names and ages, and also keep track of changes to their details in different parts of your app.

The Problem

If you try to copy all the details every time you want to update or share them, it becomes slow and confusing. You might accidentally change one copy but forget to update others, causing mistakes.

The Solution

Classes let you create one shared object that many parts of your app can use and change together. This way, updates happen in one place, keeping everything in sync easily.

Before vs After
Before
var person1 = Person(name: "Anna", age: 30)
var person2 = person1
person2.age = 31
// person1.age is still 30
After
class Person {
  var name: String
  var age: Int
  init(name: String, age: Int) {
    self.name = name
    self.age = age
  }
}

var person1 = Person(name: "Anna", age: 30)
var person2 = person1
person2.age = 31
// person1.age is now 31
What It Enables

It enables shared, changeable data that stays consistent everywhere it's used.

Real Life Example

Think of a music app where the same song object is used in playlists and the player; changing the song's info updates it everywhere instantly.

Key Takeaways

Structs copy data, so changes don't affect the original.

Classes share a single object, so changes update everywhere.

Classes are great when you want shared, changeable data.