DevPrep

All topics › Programming basics

Class

Junior

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

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

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

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store