Lesson 61Classes

Class Basics

What are Classes?

Classes are reference types that support inheritance. Unlike structs, when you assign a class instance to another variable, both variables point to the same object in memory!

Class Syntax

class ClassName {
    var property: Type

    init(property: Type) {
        self.property = property
    }
}

Class Features

Reference Type

Multiple variables can point to same object

Inheritance

Classes can inherit from other classes

Deinitializers

Cleanup when instance is deallocated

Type Casting

Check and cast types at runtime

Important Note

Classes require an explicit initializer unless all properties have default values. Unlike structs, classes don't get automatic memberwise initializers!

main.swift
// CLASS BASICS
// Classes are REFERENCE TYPES with inheritance support

// DEFINING A CLASS
class Person {
    var name: String
    var age: Int

    // Classes REQUIRE an initializer
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    func introduce() {
        print("Hi, I'm \(name), \(age) years old")
    }
}

// CREATING INSTANCES
let person1 = Person(name: "Alice", age: 25)
person1.introduce()  // Hi, I'm Alice, 25 years old

// MODIFYING PROPERTIES
person1.name = "Alice Smith"
person1.age = 26

// CLASSES CAN HAVE let PROPERTIES
class Car {
    let brand: String      // Immutable after init
    var model: String
    var year: Int

    init(brand: String, model: String, year: Int) {
        self.brand = brand
        self.model = model
        self.year = year
    }

    func description() -> String {
        return "\(year) \(brand) \(model)"
    }
}

let myCar = Car(brand: "Tesla", model: "Model 3", year: 2023)
// myCar.brand = "BMW"  // ERROR: brand is let
myCar.model = "Model Y"  // OK: model is var
print(myCar.description())

// CLASS WITH DEFAULT VALUES
class User {
    var username: String
    var email: String
    var isActive: Bool = true
    var loginCount: Int = 0

    init(username: String, email: String) {
        self.username = username
        self.email = email
    }

    func login() {
        loginCount += 1
        print("\(username) logged in (\(loginCount) times)")
    }
}

let user = User(username: "john_doe", email: "[email protected]")
user.login()  // john_doe logged in (1 times)
user.login()  // john_doe logged in (2 times)

// CLASSES VS STRUCTS - KEY DIFFERENCE
// Classes are REFERENCE types
let person2 = person1  // Both point to SAME object!
person2.name = "Bob"
print(person1.name)  // Bob (changed!)

// This is different from structs which COPY!

Try It Yourself!

Create a BankAccount class with accountNumber, balance, and methods for deposit() and withdraw()!