0
0
Swiftprogramming~5 mins

Overriding methods and properties in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Overriding methods and properties
O(1)
Understanding Time Complexity

When we override methods or properties in Swift, we want to know how this affects the time it takes for our program to run.

We ask: Does overriding change how long the program takes as it grows?

Scenario Under Consideration

Analyze the time complexity of the following Swift code using method overriding.


class Animal {
    func speak() {
        print("Animal sound")
    }
}

class Dog: Animal {
    override func speak() {
        print("Bark")
    }
}

let pet: Animal = Dog()
pet.speak()
    

This code shows a base class with a method and a subclass that overrides it. We call the method on a subclass instance typed as the base class.

Identify Repeating Operations

Look for repeated actions or calls that affect time.

  • 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 does not grow with input size.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time stays the same no matter how many objects or calls you have if you call the method once.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the overridden method call stays constant, no matter the input size.

Common Mistake

[X] Wrong: "Overriding a method makes the program slower as input grows because it adds extra steps."

[OK] Correct: Overriding just changes which code runs, but calling the method still takes the same amount of time each call.

Interview Connect

Understanding that overriding does not increase time complexity helps you explain how object-oriented features work efficiently in real programs.

Self-Check

"What if the overridden method calls a loop inside it? How would the time complexity change?"