Chapter 79: Swift Classes/Objects

1. What is a class? What is an object? (the clearest possible explanation)

Class = the blueprint / recipe / template Object = one actual thing made from that blueprint

Real-life analogy (the one that clicks for almost everyone):

  • Class = the design / blueprint of a smartphone (screen size, camera specs, battery type, how buttons work…)
  • Object = one actual phone made from that blueprint → My iPhone 14 Pro → Your iPhone 15 → Your friend’s iPhone 13

Both phones follow the same design (same class), but each phone has its own:

  • own phone number
  • own photos
  • own battery level
  • own wallpaper

That is the core idea:

Class defines what every object of that type knows and can do. Object is one concrete instance with its own specific values.

2. Creating a class – basic syntax

Swift

3. Creating objects (instances) from the class

Swift

Important memory fact:

  • rahul and priya are two separate objects
  • Changing one does not affect the other
  • Classes are reference types — variables hold references (pointers) to the object in memory

4. Real-life examples — classes you will actually write

Example 1 – BankAccount (classic encapsulation example)

Swift

Example 2 – Simple Car class (inheritance + polymorphism)

Swift

5. Very Common Beginner Mistakes & Correct Habits

Mistake Wrong / Risky code Correct / Better habit Why?
Using var for everything var name: String everywhere Default to let unless you actually reassign let prevents accidental changes + better safety
Force-unwrapping in class methods self.user!.name guard let user = user else { return } Safer, better error handling
Deep inheritance hierarchies 5+ levels of inheritance Prefer composition or protocols Deep trees become hard to maintain
Making everything public public class, public var everywhere Use internal (default) or private when possible Better encapsulation & API control
Mutating shared state without care static var sharedBalance Prefer dependency injection over singletons Singletons make testing & reasoning hard

6. Quick Summary – Classes vs Structs (the decision you make every day)

Feature / Question Class (reference type) Struct (value type) When most developers choose
Identity matters (same object, same instance) Yes — two variables can point to same object No — copying creates independent value Class when identity matters (shared state)
Inheritance supported Yes No Class when you need inheritance
Can be used as key in Dictionary/Set No (unless you implement Hashable carefully) Yes (if Hashable) Struct almost always for value types
Memory management Reference counting (ARC) Copied on write (Copy-on-Write for Array, Dict…) Struct safer for value semantics
Thread safety (mutable shared state) Can cause problems Safer (each copy independent) Struct preferred in modern Swift
Typical use in SwiftUI ObservableObject / @StateObject @State, @ObservedObject (structs) Structs for most data models

Modern Swift recommendation (2025–2026):

Use struct by default for almost everything Use class only when you need:

  • reference semantics (shared mutable state)
  • inheritance
  • Objective-C interop
  • identity comparison (===)

7. Small Practice – Try these

  1. Create a Person class with:
    • let name: String
    • var age: Int
    • method haveBirthday() that increases age
  2. Create a BankAccount class like the example above
    • private balance
    • deposit & withdraw methods
    • read-only currentBalance
  3. Create ElectricCar that inherits from Car
    • override honk() to say something electric

Paste your code here if you want feedback or want to see more polished versions!

What would you like to explore next?

  • Struct vs Class — detailed comparison & decision guide
  • Inheritance vs composition (modern preference)
  • Protocol-oriented programming (POP)
  • Access control (private, fileprivate, internal, public, open)
  • OOP in SwiftUI (ObservableObject, @StateObject…)
  • Or move to another topic (optionals, arrays, closures, switch…)

Just tell me — we’ll continue in the same clear, detailed, patient style 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *