DEV Community

Agoi Abel Adeyemi
Agoi Abel Adeyemi

Posted on

Inheritance in Swift

A class can inherit methods, properties, and other characteristics from another class. When one class inherits from another, the inheriting class is known as a subclass, and the class it inherits from is known as its superclass. A class that does not inherit from another class is known as a base class.

The above code snippet shows how the someSubclass inherited from the someClass class. Classes in Swift can call and access methods and properties belonging to their superclass and can provide their own overriding versions of those methods and properties to refine or modify their behavior. Classes can also add property observers to inherited properties in order to be notified when the value of a property changes.

Accessing Superclass Properties and Methods

Assuming we have a base class named Person and a Youtuber class that inherit from the Person class

The first thing I want us to notice is the class Youtuber: Person{}. We simply said the Youtuber be a type of Person which make it inherit all the properties and method of the Person class.

Secondly, when we initialize the Subclass, we use the super.init() method to pass the parameters needed by the superclass constructor since a Youtuber is actually still a Person.

We can access the celebrateBirthday() method of the Person class from the Youtuber subclass like below

Overriding Methods

At times, the subclass might wish to override a method contained in a superclass. We will make use of the override keyword within the subclass like below:

I initialized the Person class as well as the Youtuber class, the celebrateBirthday method in the Person class will return a different value to the Youtuber class because of the override function that print a different content in the Youtuber class.

Overriding Properties

we have seen how to override methods in swift, but there are cases where we actually need to override properties.

Immediately after the super.init() in the inside init method, we set the country variable. Note that, we can only do this after we have initialize the superclass.

Preventing Override

We can prevent a method or property from been overridden by a subclass by using the keyword final func or final var.

There is more to inheritance like observers. Didn’t cover that here because am not pretty sure how to use it now. Will update this article when I fully understand the concept. Lemme go read up enum and optionals. Yes, will write about it when done.

_I am happy to share this article with you.

Top comments (0)