Swift Inheritance & Overriding

In swift, inheritance means acquiring the properties from parent class to child class. By using inheritance, a class can inherit properties, methods and other characteristics from another class.

 

In inheritance, the class which is inheriting properties, methods from another class is called a subclass and the class which contains propertiesmethods, and functions to inherit other classes is called a superclass.

 

The classes in swift can inherit the propertiesmethods, and functions from the super class using inheritance and can implement custom functionality in sub class by overriding the properties and methods of super class based on our requirements. Swift will ensure overrides are correct by checking that the override definition has a matching super class definition.

 

In classes, we can add property observers to inherited properties to notify about the changes made for the properties.

Swift Base Class

In swift, a class that doesn’t inherit propertiesmethods or functions from any other class is called as a Base Class.

 

Now we will see how to define base class in swift programming language with examples. 

 

Following is the example of defining base class with properties and methods in swift programming language.

 

class person {

var Name: String = ""

var Age:Int = 0

var Gender: String = ""

init(Name: String, Age: Int, Gender:String)

{

self.Name=Name

self.Gender=Gender

self.Age=Age

}

}

let p = person.init(Name: "Suresh Dasari", Age: 30, Gender: "Male")

print(p.Name,p.Age,p.Gender)

If you observe above example we defined a base class “person” with properties like Name, Age, Gender and init method to initialize property values.

 

When we run above example in swift playground we will get result like as shown below

 

Suresh Dasari 30 Male

This is how we can define a base class in a swift programming language based on our requirements.

Swift Sub Class

In swift, a class which is inheriting properties or methods from other existing class is called as a subclass. In subclass we can override the properties or methods of base or existing class with the same definition based on our requirements.

 

In swift we can define subclass by using colon (“:”) before the base class name. Following is the syntax of defining subclass in a swift programming language.

 

class subclass: superclass {

// subclass implementation here 

}

In above syntax we defined subclass name before the superclass and both are separated by a colon (“:”). In subclass we can inherit the properties or methods from superclass based on our requirements.

 

Now we will see how to represent base class and subclass in the inheritance with example. Suppose we make a school management system in which there are many members who perform their duties in schools like Teacher, Student, Non-teaching Staff and etc. All members have their own attributes like Name, Age, Gender and etc. and in class level, these are common in Teacher, Student and Non-teaching Staff so we will create a separate class for those common attributes or methods and we will apply inheritance concept to inherit common properties or methods from new base class.

 

Following is the pictorial representation of defining our school management system using the inheritance concept.

 

Swift Inheritance Example

 

If you observe above image we defined common properties in separate class and inheriting that base class properties into other classes. 

 

Following is the syntax of representing our school management system using inheritance. Here we defined all the common properties in Person class as a parent or base class and inheriting base class into other classes like Teacher, Student and Nonteaching.

 

class Person {

// implementation here

}

class Teacher: Person {

// Subclass implementation here

}

class Student: Person {

// Subclass implementation here

}

class Nonteaching: Person {

// Subclass implementation here

}

Now we will see how to use base class and subclasses in our school management system with examples in swift programming language.

 

Following is the example of implementing inheritance for our school management system in a swift programming language.

 

class person {

var Name: String = ""

var Age:Int = 0

var Gender: String = ""

init(Name: String, Age: Int, Gender:String)

{

self.Name=Name

self.Gender=Gender

self.Age=Age

}

}

class student : person { }

class teacher : person { }

class nonteaching: person { }

let stu = student.init(Name: "Suresh Dasari", Age: 30, Gender: "Male")

print(stu.Name,stu.Age,stu.Gender)

let t = teacher.init(Name: "Rohini Alavala", Age: 30, Gender: "Female")

print(t.Name,t.Age,t.Gender)

let nt = nonteaching.init(Name: "Trishika Dasari", Age: 1, Gender: "Female")

print(nt.Name,nt.Age,nt.Gender)

If you observe above example we defined a one base class “person” and three subclasses (student, teacher, nonteaching) inheriting properties from person base class.

 

When we run the above code in swift playground we will get a result like as shown below

 

Suresh Dasari 30 Male

Rohini Alavala 30 Female

Trishika Dasari 1 Female

This is how we can use inheritance in swift programming language to inherit properties from parent class to child class based on our requirements.

Swift Overriding

In swift, Overriding is the process in which subclass is fully responsible to change or re-implement the instance method, instance property and type property which is defined in parent class or superclass. 

 

A subclass provides fully custom implementation for any type including instance method or property of super class based on our requirements. 

 

In swift to override inherited properties or methods in subclass we use override keyword which will tells the compiler to check the overriding method or property definition matches with the base class or not.

Syntax of Swift Overriding

Following is the syntax of overriding inherited properties or methods in subclass using override keyword.

 

class Sample1 {

func Name() {

// Function implementation here

}

}

class Sample2: Sample1 {

override func Name() {

// Override function implementation here

}

}

If you observe above syntax we defined base class “Sample1” and inheriting base class properties and methods in subclass “Sample2” and overriding function in subclass using override keyword.

Swift Overriding Methods

By using inheritance we can inherit base class properties, methods in a subclass and override base class properties or methods in subclass based on our requirements.

 

By using override keyword in subclass we can override a base class methods with the same base class declaration.

 

Following is the example of inheriting properties from base class to subclass and overriding base class method in subclass using override keyword.

 

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()

If you observe above example we defined a base class “Class1” with function “FullName” and inherited base class properties to subclass “Class2” and overridden base class function “FullName” in subclass based on our requirements.

 

When we run above example in swift playground we will get a result like as shown below

 

It’s a Super Class

It’s a Sub Class

This is how we can override methods in swift programming language based on our requirements.

Swift Overriding Properties

In swift, we can override inherited properties of base class in the subclass to provide our own custom getter and setters for the properties or add property observers to the overriding properties to observe when the property value changes based on our requirements.

 

By defining custom getter and setter for properties in subclass we can inherit the base class properties

 

Following is the example of overriding base class inherited properties in a subclass which is defined in a swift programming language.

 

class OldStudent {

var studentFee = 800

var Fee: String {

return "The Old Fee is \(studentFee)"

}

}

class NewStudent: OldStudent {

var amount = 1000

override var Fee: String {

return super.Fee + ", the override New Fee is \(amount)"

}

}

let newstudent = NewStudent()

newstudent.studentFee = 800

newstudent.amount = 1000

print("\(newstudent.Fee)")

If you observe example we are overriding base class “OldStudent” properties in subclass “NewStudent” based on our requirements.

 

When we run above example in swift playground we will get a result like as shown below

 

The Old Fee is 800, the override New Fee is 1000

Following is the example of overriding base class properties in subclass using custom getter and setter values.

 

class OldStudent {

var studentFee = 800

var Fee: String {

return "The Old Fee is \(studentFee)"

}

}

class NewStudent: OldStudent {

var _fee: String = ""

var amount = 1000

override var Fee: String {

get {

return super.Fee + ", the override New Fee is \(amount)"

}

set {

_fee = newValue

}

}

}

let newstudent = NewStudent()

newstudent.studentFee = 800

newstudent.amount = 1000

print("\(newstudent.Fee)")

If you observe example we are overriding base class “OldStudent” properties in subclass “NewStudent” using getter and setter properties based on our requirements.

 

When we run above example in swift playground we will get result like as shown below

 

The Old Fee is 800, the override New Fee is 1000

This is how we can override properties using custom getter and setters in a swift programming language based on our requirements.

Swift Overriding Property Observers

By using property overriding we can add property observer to our inherited property. This enables us to alert when the inherited property value is changed. 

 

Following is the example of adding property observers to the inherited property to know the changes made to an override property.

 

class OldStudent {

var studentFee = 800

var Fee: String {

return "The Old Fee is \(studentFee)"

}

}

class NewStudent: OldStudent {

var amount = 1000

override var Fee: String {

return super.Fee + ", Override New Fee is \(amount)"

}

}

let newstudent = NewStudent()

newstudent.studentFee = 800

newstudent.amount = 1000

print("\(newstudent.Fee)")

class FinancialAdstudent: NewStudent {

override var studentFee: Int {

didSet {

amount = Int(studentFee/2)

}

}

}

let fiaddstu = FinancialAdstudent()

fiaddstu.studentFee = 500

print("Financial Ad Fee is \(fiaddstu.studentFee)")

If you observe above example we added property observers using didSet and capturing whenever the inherited property value changes.

 

When we run above example in swift playground we will get a result like as shown below

 

The Old Fee is 800, Override New Fee is 1000

Financial Ad Fee is 500

This is how we can override a property observers in swift programming language based on our requirements.

Swift Prevent Overriding

In swift, we can prevent our methods, properties or subscripts from being overridden by using final keyword modifiers along with their methods and properties. Before the start of our method or variable, we just declare the final keyword. After declaring the final modifier when we try to override it compiler gives a Compile time error. We can also mark a whole class by final modifier. 

 

Here is the example, in which we declare fee variable as a final keyword when we try to override the fee variable compiler gives an error.

 

Swift Prevent a Property Overriding with Example

 

This is how we can use inheritance and overriding in classes to inherit properties from one class to another class and override the inherited properties or methods based on our requirements in swift programming language.