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?