Swift Method Overriding: Enhancing Subclass Functionality

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
June 10, 2024

Swift Method Overriding

In Swift, method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This feature is crucial for enabling polymorphism, where different objects can be treated as instances of a common superclass during runtime. Method overriding is achieved by using the 'override' keyword before the subclass method's implementation.


class Vehicle {
    func makeSound() {
        print("Generic sound")
    }
}

class Car: Vehicle {
    override func makeSound() {
        print("Vroom Vroom")
    }
}

let vehicle = Vehicle()
let car = Car()

vehicle.makeSound()  // Output: Generic sound
car.makeSound()      // Output: Vroom Vroom


How Method Overriding Works

When a subclass overrides a method from its superclass, the subclass method replaces the implementation of the superclass method when the subclass instance is used. In the example above, the 'Car' class overrides the 'makeSound' method from its superclass 'Vehicle' to provide a custom sound specific to cars.

Rules for Method Overriding in Swift:

  1. The method in the subclass must have the 'override' keyword before its implementation.
  2. The method signatures (name and parameters) in the superclass and subclass must match.
  3. The access control level of the subclass method cannot be more restrictive than the superclass method's access level.

Method overriding is commonly used in Swift to customize the behavior of subclasses while maintaining a common interface defined in the superclass. It allows for flexibility in object-oriented programming and promotes code reusability and maintainability.