SwiftUI Tutorial: Understanding class in Swift

1. What is a Class?

A class is a reference type in Swift. It's used to create objects with shared behavior and identity.

Classes allow inheritance, reference semantics, and deinitialization.

2. Basic Syntax of a Class

class Person {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    func greet() {
        print("Hello, my name is \\(name)")
    }
}

3. Reference vs Value Type (class vs struct)

class MyClass {
    var number = 0
}
var a = MyClass()
var b = a
b.number = 42
print(a.number) // Outputs: 42

4. Using Classes with SwiftUI

Use ObservableObject to make classes interact with SwiftUI views.

import SwiftUI

class CounterModel: ObservableObject {
    @Published var count = 0

    func increment() {
        count += 1
    }
}

Now use it in a SwiftUI view:

struct CounterView: View {
    @StateObject var model = CounterModel()

    var body: some View {
        VStack {
            Text("Count: \\(model.count)")
            Button("Increment") {
                model.increment()
            }
        }
        .padding()
    }
}

5. Inheritance and Method Overriding

class Animal {
    func speak() {
        print("Animal sound")
    }
}

class Dog: Animal {
    override func speak() {
        print("Bark!")
    }
}

let pet = Dog()
pet.speak() // Outputs: Bark!

6. Deinitialization

class Logger {
    init() {
        print("Logger initialized")
    }

    deinit {
        print("Logger deallocated")
    }
}

Deinitializers run when the object is deallocated. This is useful for cleanup, closing files, etc.