What is the difference between overriding a method and overloading a method in Swift?
iOS interview question for Intermediate practice.
Answer
Overriding and overloading are two distinct concepts in Swift related to methods (and functions/properties) that share the same name, but they occur in different contexts and serve different purposes: Overriding: Context: Occurs only in the context of class inheritance. What it is: A subclass provides its own specific implementation for a method (or computed property, subscript) that it inherits from its superclass. Signature: The overriding method in the subclass must have the exact same name, parameter types, and return type as the method in the superclass. Keyword: Requires the override keyword before the method definition in the subclass. Purpose: To specialize or modify the behavior defined by the superclass for the subclass (runtime polymorphism). Example: swift class Animal { func makeSound() { print("...") } } class Dog: Animal { override func makeSound() { print("Woof!") } // Overrides superclass method } Overloading: Context: Occurs within the same scope (e.g., within the same class, struct, enum, or global scope). What it is: Defining multiple methods (or functions) with the same name, but with different parameter lists (different number, types, or external labels of parameters). Signature: Overloaded methods have the same name but different function signatures (excluding the return type). Keyword: Does not use a special keyword like override. Purpose: To provide multiple versions of a method that perform a similar conceptual task but accept different kinds or amounts of input. Example: swift struct Calculator { func add( a: Int, b: Int) - Int { a + b } // Overload with different type func add( a: Double, b: Double) - Double { a + b } // Overload with different number of parameters func add( a: Int, b: Int, c: Int) - Int { a + b + c } } In Summary: | Feature | Overriding | Overloading | | :------------ | :------------------------------- | :----------------------------------- | | Context | Class Inheritance (Subclass) | Same Scope (Same Type/File) | | Relation | Replaces superclass method | Different methods with same name | | Signature | Same signature as superclass | Different parameter signatures | | Keyword | override | None | | Purpose | Specialize inherited behavior | Provide variations for input types | | Applies To| Classes only | Functions, Methods, Inits, Subscripts|
Explanation
You can overload a method that was inherited from a superclass, but if you want to change the implementation for the exact same signature as the superclass method, you must use override.