Coding/Learn/swift/swift classes inheritance and deinit
Swift Foundational Course
01.Introduction, Safety Philosophy & The Toolchain
02.Constants (let), Variables (var) & Type Inference
03.Strings, String Interpolation & Multiline Literals
04.Operators, Range Types & Nil-Coalescing
05.Control Flow: If, Switch Pattern Matching & Guard Statements
06.Optionals, Optional Binding & Optional Chaining
07.Arrays, Sets & Higher-Order Collection Operations
08.Dictionaries, Default Lookups & Tuples
09.Loops, Defer Execution & Labeled Statements
10.Functions, Argument Labels & In-Out Parameters
11.Closures, Trailing Closures & Shorthand Arguments
12.Enums, Raw Values & Associated Values (Tagged Unions)
13.Error Handling: Throwing Functions, Do-Catch & Try Options
14.Structures (struct), Value Semantics & Mutating Methods
15.Classes, Reference Semantics & Inheritance
16.Automatic Reference Counting (ARC), Weak & Unowned References
17.Properties: Stored, Computed, Observers (didSet) & Lazy
18.Protocols, Protocol Extensions & POP (Protocol-Oriented Programming)
19.Generics, Type Constraints & Associated Types
20.Capstone: Production Async/Await Cache & JSON API Engine
Course Certificate0%

Complete all lessons to earn

LearnClasses, Reference Semantics & Inheritance
15 / 20 0%
Lesson 15 of 20
10 mins read

Classes, Reference Semantics & Inheritance

PreviousNext Lesson
In Plain English

When you need shared mutable state or single-inheritance hierarchies, use Classes. Master reference semantics (multiple variables pointing to the same instance), custom initializers, subclassing with extends, super.init calls, and deinitializers (deinit).

The Mental Model

"A class instance is like a Google Doc: when you share the link with 5 team members, everyone edits the exact same live document. Changes made by any member are instantly visible to everyone."

Deep Dive: How It Works

Reference Semantics: Assigning a class instance to a new variable creates another reference to the exact same object in memory.

Identity Operator (===): Checks whether two variables point to the exact same memory address (unlike == which checks value equality).

Inheritance: Subclasses inherit methods and properties from a superclass (class Manager: Employee).

Deinitializer (deinit): Executes automatically when an instance reference count drops to zero and memory is deallocated.

Syntax Blueprint

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

Inherit with : BaseClass and override methods with the override keyword.

PointCore Rules to Remember

Point star
Reference Types: Variables hold pointers to memory allocated on the heap.
Point star
Required Initializers: Subclasses must call super.init() after initializing their own stored properties.
Point star
Final Classes: Prefix with final class to disallow subclassing and enable static method dispatch optimization.

Common Beginner Traps & How to Fix Them

Mistake:Forgetting the override keyword when redefining a superclass method.

Why it happens: Swift compiler requires explicit override to prevent accidental method shadowing.

How to fix: Add the override keyword before func.

Pro Tip: Use final on classes whenever inheritance is not explicitly planned to improve compiler optimization.

Live Interactive Example

Hit Run Code to see it live
Class Reference Semantics and Inheritance
Swift 5.10 / LLVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Output Console
Click "Run Code" to view the rendered output.
How it works: Mutating v2.speed updated v1 because both reference the exact same heap instance.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Create an Account Class Hierarchy

  • PointCreate a class Account with var balance: Double and an init(balance: Double).
  • PointCreate a subclass PremiumAccount: Account with a method addBonus(amount: Double) that adds amount to balance.
  • PointIn top-level code, create let acc = PremiumAccount(balance: 100.0), call acc.addBonus(amount: 25.0), and print "Balance: $\(acc.balance)".
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates