Chapter 83: Swift Class Methods

1. What is a method in a class?

A method is simply a function that belongs to a class (or struct/enum).

There are two kinds:

  1. Instance methods → Belong to each individual object (instance) → Called on an instance: myObject.doSomething()
  2. Type methods (static / class methods) → Belong to the type itself (the class), not to any particular instance → Called on the type name: MyClass.doSomething()

Think of it like this:

  • Instance method = “Each person can tell you their own name” → rahul.introduce() → “I’m Rahul” → priya.introduce() → “I’m Priya”
  • Type method = “The Person class can tell you something about all people” → Person.averageAge() → “Average age of all people is 28”

2. Instance Methods – the most common type

These are the normal methods you write inside a class.

Swift

Key points about instance methods:

  • They have implicit access to self (the current instance)
  • They can read and modify instance properties (if var)
  • They are called on an instance: rahul.introduce()

3. Type Methods — static & class methods

These belong to the type itself, not to any specific object.

There are two kinds:

  • static — cannot be overridden in subclasses
  • class — can be overridden in subclasses
Swift

4. Real-life examples — class methods you will actually write

Example 1 – Factory methods (very common pattern)

Swift

Example 2 – Shared / singleton-like (careful — use sparingly)

Swift

Modern note: Singletons are used less in modern Swift. Prefer dependency injection instead.

5. Very Common Beginner Mistakes & Correct Habits

Mistake Wrong / Risky code Correct / Better habit Why?
Using var for properties that never change var id: UUID let id: UUID let prevents accidental changes
Force-unwrapping in methods self.user!.name guard let user = user else { return } Safer, better error handling
Making everything public public class, public var everywhere Default = internal — use public only when needed Better encapsulation & API control
Forgetting mutating in struct methods func increase() { age += 1 } mutating func increase() { age += 1 } Compile error if missing (structs only)
Overusing class inheritance Deep class hierarchies Prefer composition + protocols Easier to test, understand, maintain

6. Quick Summary — Class Properties Patterns You Will Use Most

Goal Typical code When to prefer it
Fixed data (identity) let id: UUID, let createdAt: Date Always use let when value never changes
Changeable data var balance: Double, var status: String When value needs to be updated
Calculated value var fullName: String { first + ” ” + last } When value depends on other properties
Expensive object created only when needed lazy var formatter = DateFormatter() Heavy initialization (formatters, images, etc.)
React to value change var score: Int { didSet { updateUI() } } UI updates, saving, logging, validation
Read-only public view of private data private var _balance: Double + var balance: Double { _balance } Encapsulation + controlled access

7. Small Practice – Try these

  1. Create a Person class with:
    • let id: UUID
    • var name: String
    • var age: Int
    • computed property isAdult: Bool
    • method haveBirthday()
  2. Create a BankAccount class with:
    • private var balance: Double
    • init(initialDeposit:)
    • var currentBalance: Double (computed)
    • methods deposit(amount:) and withdraw(amount:) -> Bool
  3. Create a TemperatureMonitor class with:
    • var celsius: Double { didSet { checkWarning() } }
    • private method checkWarning() that prints warning if > 40 or < 10

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
  • Mutability inside structs (mutating methods)
  • Struct initializers (default, custom, memberwise)
  • Structs in SwiftUI (@State, value types, performance)
  • 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 *