Class
Essence
A class describes a type of objects: their properties, methods and initialisers. It is the blueprint instances are built from. In Swift a class is a reference type: the instance lives on the heap, variables hold a reference to it, and ARC manages its lifetime.
What makes a class special in Swift
- Reference semantics:
let b = agives two references to one object; a change throughbis visible througha. - Inheritance (single):
overrideof methods and properties,super;finalforbids subclassing and speeds up calls (static dispatch instead of vtable). - Initialisers: designated/convenience, two-phase initialisation, every property must have a value before
super.init. deinitruns when the object is freed; structs have none.- Identity:
===,ObjectIdentifier. - Objective-C interoperability: only classes can inherit from
NSObjectand be@objc.
class Animal {
let name: String
init(name: String) { self.name = name }
func sound() -> String { "..." }
deinit { print("\(name) released") }
}
final class Dog: Animal { // final: no further subclassing
override func sound() -> String { "Woof" }
}
func demo() {
var pet: Animal? = Dog(name: "Rex")
let same = pet // a second reference to the same object
print(pet!.sound()) // Woof — dynamic dispatch
pet = nil // the object is alive: `same` holds it
print(same?.name ?? "nil") // Rex
} // same goes away → "Rex released"
Class vs struct — the follow-up question
struct: copied, no inheritance (protocols instead), nodeinit, usually on the stack,Sendableby default when all fields areSendable.class: a reference, inheritance,deinit, heap + ARC; in Swift 6 passing it between threads needs@MainActor/actoror manual synchronisation.
Apple recommends starting with a struct and using a class when you need identity (a shared mutable resource, a controller, a cache), inheritance from system classes (UIView, NSObject) or deinit.
What the interviewer looks for
- Do you know that
leton a class fixes the reference, not the contents. - Do you understand why
finalexists (performance, closed for extension) and howclass funcdiffers fromstatic func(the former can be overridden). - Can you explain a retain cycle: two objects holding strong references to each other never reach
deinit; the cure isweak/unowned.