Base class and subclass in Swift - Time & Space Complexity
When using base classes and subclasses, it's important to see how the program's work grows as input changes.
We want to know how the time to run the code changes when we create or use many objects.
Analyze the time complexity of the following code snippet.
class Animal {
func speak() {
print("Animal sound")
}
}
class Dog: Animal {
override func speak() {
print("Bark")
}
}
let dogs = (1...n).map { _ in Dog() }
dogs.forEach { $0.speak() }
This code creates n Dog objects and calls their speak method one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating n Dog objects and calling speak on each.
- How many times: The speak method is called once for each Dog, so n times.
As the number of Dog objects increases, the total work grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 speak calls |
| 100 | About 100 speak calls |
| 1000 | About 1000 speak calls |
Pattern observation: Doubling n doubles the work because each object is handled once.
Time Complexity: O(n)
This means the time grows directly with the number of objects created and used.
[X] Wrong: "Because of inheritance, the code runs slower exponentially as n grows."
[OK] Correct: Inheritance itself does not add extra loops or repeated work; each object is still handled once.
Understanding how subclassing affects time helps you explain object-oriented code performance clearly and confidently.
"What if the speak method called another method that loops over all dogs? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of a base class
A base class defines common properties and methods that other classes can reuse.Step 2: Compare options with this role
To provide a general template for other classes to build upon correctly states the base class is a general template. Other options describe incorrect or unrelated roles.Final Answer:
To provide a general template for other classes to build upon -> Option BQuick Check:
Base class = general template [OK]
- Thinking base class cannot be inherited
- Confusing base class with instances
- Assuming base class only stores data
Dog inheriting from a base class Animal in Swift?Solution
Step 1: Recall Swift subclass syntax
In Swift, a subclass is declared using a colon (:) after the subclass name followed by the base class name.Step 2: Match options to syntax
class Dog: Animal { } usesclass Dog: Animal { }, which is correct. Other options use incorrect keywords or symbols.Final Answer:
class Dog: Animal { } -> Option CQuick Check:
Subclass syntax = colon (:) [OK]
- Using 'inherits' or 'extends' keywords (not Swift)
- Using wrong symbols like <
- Omitting the colon between subclass and base class
class Vehicle {
func sound() -> String {
return "Vroom"
}
}
class Car: Vehicle {
override func sound() -> String {
return "Beep"
}
}
let myCar = Car()
print(myCar.sound())What will be printed when this code runs?
Solution
Step 1: Understand method overriding in subclass
The subclassCaroverrides thesound()method to return "Beep" instead of the base class "Vroom".Step 2: Identify which method is called
When callingmyCar.sound(), the overridden method inCarruns, returning "Beep".Final Answer:
"Beep" -> Option AQuick Check:
Overridden method runs = "Beep" [OK]
- Expecting base class method output
- Confusing method override with overload
- Thinking print shows class name
class Animal {
func speak() {
print("Animal sound")
}
}
class Cat: Animal {
func speak() {
print("Meow")
}
}Solution
Step 1: Check method overriding rules in Swift
When a subclass provides its own version of a base class method, it must use theoverridekeyword.Step 2: Identify missing override keyword
Thespeak()method inCatlacksoverride, causing a compile error.Final Answer:
Missing override keyword before speak() in subclass -> Option DQuick Check:
Override keyword required for method override [OK]
- Forgetting override keyword
- Thinking subclass methods cannot have same name
- Assuming class names must be lowercase
Employee with a property name and a method work() that prints "Working". Then create a subclass Manager that overrides work() to print "Managing team" and adds a new method holdMeeting() that prints "Meeting started".Which code correctly implements this?
Solution
Step 1: Check base class implementation
The base classEmployeemust have anameproperty with initializer and awork()method printing "Working". class Employee { var name: String init(name: String) { self.name = name } func work() { print("Working") } } class Manager: Employee { override func work() { print("Managing team") } func holdMeeting() { print("Meeting started") } } and C have correct base class with initializer.Step 2: Check subclass overrides and new method
The subclassManagermust overridework()withoverridekeyword and addholdMeeting(). class Employee { var name: String init(name: String) { self.name = name } func work() { print("Working") } } class Manager: Employee { override func work() { print("Managing team") } func holdMeeting() { print("Meeting started") } } correctly usesoverrideand addsholdMeeting(). class Employee { var name: String init(name: String) { self.name = name } func work() { print("Working") } } class Manager: Employee { func work() { print("Managing team") } func holdMeeting() { print("Meeting started") } } missesoverride. class Employee { var name: String func work() { print("Working") } } class Manager: Employee { func work() { print("Managing team") } func holdMeeting() { print("Meeting started") } } misses initializer in base class. class Employee { var name: String init(name: String) { self.name = name } func work() { print("Working") } } class Manager: Employee { override func work() { print("Managing team") } } missesholdMeeting().Final Answer:
Option A code correctly implements all requirements -> Option AQuick Check:
Override + new method + initializer = class Employee { var name: String init(name: String) { self.name = name } func work() { print("Working") } } class Manager: Employee { override func work() { print("Managing team") } func holdMeeting() { print("Meeting started") } } [OK]
- Forgetting override keyword in subclass
- Missing initializer in base class
- Not adding new methods in subclass
Ready to prove it?
Pass the test and this pattern moves unknown
