Classes provide reference semantics, inheritance, and deinitializers—use when instances must share identity (view controllers, network clients) or you need subclassing.
Class basics
class Counter {
var count = 0
func increment() { count += 1 }
}
let a = Counter()
let b = a
b.increment()
print(a.count) // 1 — shared instance
Inheritance
class Animal {
func speak() { print("...") }
}
class Dog: Animal {
override func speak() { print("woof") }
}
Swift classes support single inheritance; protocols fill multiple-behavior needs.
Important interview questions and answers
- Q: When use class over struct?
A: Shared mutable state, Objective-C interop, inheritance, or ARC-managed resources tied to instance lifetime. - Q: final keyword?
A: Prevents subclassing or overriding—default for performance and API stability in many frameworks.
Self-check
- Do two variables referencing one class instance share mutations?
- How many superclasses can a Swift class have?
Tip: Use classes when instances must share identity—view controllers, delegates, network clients.
Interview prep
- When use class?
Shared identity, inheritance, Objective-C interop, or ARC-managed resources.
- Inheritance limit?
Single superclass—protocols for multiple behaviors.