0
0
Swiftprogramming~5 mins

Preventing overrides with final in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Preventing overrides with final
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the speak() method once.
  • How many times: Exactly one time in this example.
How Execution Grows With Input

Since the method is called once, the time to run does not grow with input size.

Input Size (n)Approx. Operations
1010 calls, each direct and fixed time
100100 calls, each direct and fixed time
10001000 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.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how final affects method calls helps you explain how Swift optimizes code and why some choices make programs faster.

Self-Check

What if the speak() method was not marked final and was overridden in subclasses? How would the time complexity change?