Preventing overrides with final in Swift - Time & Space Complexity
Let's see how using final affects the time it takes for Swift to run code involving class methods.
We want to know if marking methods as final changes how the program's speed grows with bigger inputs.
Analyze the time complexity of the following code snippet.
class Animal {
final func speak() {
print("Animal sound")
}
}
class Dog: Animal {
// Cannot override speak() because it's final
}
let dog = Dog()
dog.speak()
This code defines a method that cannot be changed by subclasses, then calls it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
speak()method once. - How many times: Exactly one time in this example.
Since the method is called once, the time to run does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls, each direct and fixed time |
| 100 | 100 calls, each direct and fixed time |
| 1000 | 1000 calls, each direct and fixed time |
Pattern observation: The time grows directly with the number of calls, but each call is simple and fast because final avoids extra checks.
Time Complexity: O(n)
This means the total time grows in a straight line with how many times you call the method, and each call is quick because it is fixed and direct.
[X] Wrong: "Using final makes the method run instantly no matter how many times it's called."
[OK] Correct: Even with final, each call takes some time, so if you call it many times, total time still grows.
Understanding how final affects method calls helps you explain how Swift optimizes code and why some choices make programs faster.
What if the speak() method was not marked final and was overridden in subclasses? How would the time complexity change?
Practice
What does the final keyword do in Swift?
Solution
Step 1: Understand the purpose of
Thefinalfinalkeyword in Swift is used to stop classes or methods from being changed by subclasses.Step 2: Identify what
It prevents overriding methods or subclassing classes, ensuring the code stays as originally designed.finalpreventsFinal Answer:
Prevents a class or method from being overridden or subclassed -> Option DQuick Check:
finalstops overrides = A [OK]
- Confusing final with constant variables
- Thinking final allows subclassing
- Mixing final with async keyword
Which of the following is the correct way to declare a method that cannot be overridden in Swift?
class Vehicle {
_____ func startEngine() {
print("Engine started")
}
}Solution
Step 1: Identify the keyword to prevent overriding
In Swift, thefinalkeyword is used before a method to stop it from being overridden in subclasses.Step 2: Check the method declaration
Placingfinalbeforefunccorrectly marks the method as non-overridable.Final Answer:
final -> Option CQuick Check:
Usefinalbefore func to prevent override [OK]
- Using override keyword incorrectly
- Confusing static with final
- Using mutating which is for structs
What will happen when you run this Swift code?
class Animal {
final func sound() {
print("Animal sound")
}
}
class Dog: Animal {
override func sound() {
print("Bark")
}
}
let pet = Dog()
pet.sound()Solution
Step 1: Identify the use of final in the base class
The methodsound()inAnimalis marked asfinal, so it cannot be overridden.Step 2: Check the subclass method override
TheDogclass tries to overridesound(), which causes a compile-time error because overriding a final method is not allowed.Final Answer:
Compile-time error due to overriding a final method -> Option BQuick Check:
Overriding final method = Compile error [OK]
- Assuming it prints "Bark"
- Thinking it prints base method output
- Expecting runtime error instead of compile error
Find the error in this Swift code and fix it:
final class Vehicle {
func drive() {
print("Driving")
}
}
class Car: Vehicle {
override func drive() {
print("Car driving")
}
}Solution
Step 1: Identify the use of final on the Vehicle class
TheVehicleclass is marked asfinal, so it cannot be subclassed.Step 2: Check subclass declaration
TheCarclass tries to subclassVehicle, which causes a compile-time error because subclassing a final class is not allowed.Final Answer:
Removefinalfrom Vehicle class -> Option AQuick Check:
Subclassing final class = Error; remove final [OK]
- Trying to override without removing final
- Adding final to subclass instead of base
- Changing class to struct unnecessarily
You want to create a base class BankAccount with a method calculateInterest() that should never be changed by subclasses. However, subclasses can add new methods. How should you declare BankAccount and calculateInterest()?
Solution
Step 1: Understand the requirement for subclassing
The base classBankAccountshould allow subclasses, so it must NOT befinal.Step 2: Protect the method from being overridden
MarkcalculateInterest()asfinalto prevent subclasses from changing it.Final Answer:
DeclareBankAccountnormally andcalculateInterest()asfinal-> Option AQuick Check:
final method, normal class = C [OK]
- Making the whole class final, blocking subclassing
- Not marking method as final, allowing override
- Using struct instead of class incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
