Introduction
Overriding in Swift is when a subclass is responsible for changing or re-implementing the instance method, instance property, and type property defined in the parent class or superclass. Based on our requirements, a subclass provides a fully customized implementation for any type, including instance methods and properties of the superclass. In Swift, we utilize the override keyword to override inherited properties or methods in subclasses. This tells the compiler whether the overriding method or property description matches the base class or not.
The subclass inherits the superclass's methods and properties in Swift Inheritance. This lets subclasses have direct access to members of the superclass. When the same method is declared in both the superclass and the subclass, the subclass method takes precedence over the superclass method. Overriding is the term for this. To declare method overriding, we utilize the override keyword. As an example,
class Vehicle {
func displayInfo(){
...
}
}
class Car: Vehicle {
// override method
override func displayInfo() {
...
}
}
The Car subclass's displayInfo() method overrides the Vehicle superclass's displayInfo() method.
Syntax:
class Sample1 {
func Name() {
// Function implementation here
}
}
class Sample2: Sample1 {
override func Name() {
// Override function implementation here
}
}
In the above syntax, we defined base class "Sample1" and subclass "Sample2," inheriting base class properties and methods and overriding functions in the subclass using the override keyword.
Swift Overriding Methods
We can inherit base class properties and subclass methods and override base class properties or subclass methods based on our needs by using inheritance. We can override a base class method with the same class declaration by using the override keyword in a subclass. The following is an example of inheriting properties from a base class to a subclass and using the override keyword to override a base class method in a subclass.
class Class1 {
func FullName() {
print("It’s a Super Class")
}
}
class Class2: Class1 {
override func FullName() {
print("It’s a Sub Class")
}
}
let s1 = Class1()
s1.FullName()
let s2 = Class2()
s2.FullName()
As you can see in the example above, we created a base class "Class1" with the function "FullName," inherited base class properties from subclass "Class2," and overridden the base class function "FullName" in the subclass based on our needs.