class
in SwiftA 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.
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)")
}
}
init
: Custom initializerself
: Refers to the current instancefunc
: Method declarationclass MyClass {
var number = 0
}
var a = MyClass()
var b = a
b.number = 42
print(a.number) // Outputs: 42
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()
}
}
@StateObject
: Tells SwiftUI to manage the lifecycle of the class@Published
: Makes SwiftUI re-render the view when this property changesclass Animal {
func speak() {
print("Animal sound")
}
}
class Dog: Animal {
override func speak() {
print("Bark!")
}
}
let pet = Dog()
pet.speak() // Outputs: Bark!
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.