Swift inheritance


Release date:2023-12-02 Update date:2023-12-08 Editor:admin View counts:114

Label:

Swift inheritance

Inheritance can be understood as one class getting the methods and properties of another class.

When a class inherits other classes, the inherited class is called a subclass, and the inherited class is called a superclass (or parent class).

In Swift, classes can call and access superclass methods, properties, and subscript scripts, and can override them.

We can also add a property watcher to the inherited properties in the class.

Base class

A class that does not inherit another class is called a Base Class.

In the following example, we define the base class StudDetails describing the student (stname) and his scores in each subject (mark1, mark2, mark3):

class StudDetails {
    var stname: String!
    var mark1: Int!
    var mark2: Int!
    var mark3: Int!
    init(stname: String, mark1: Int, mark2: Int, mark3: Int) {
        self.stname = stname
        self.mark1 = mark1
        self.mark2 = mark2
        self.mark3 = mark3
    }
}
let stname = "swift"
let mark1 = 98
let mark2 = 89
let mark3 = 76

let sds = StudDetails(stname:stname, mark1:mark1, mark2:mark2, mark3:mark3);

print(sds.stname)
print(sds.mark1)
print(sds.mark2)
print(sds.mark3)

The output of the above program execution is as follows:

swift
98
89
76

Subclass

A subclass refers to creating a new class based on an existing class.

To indicate the superclass of a class, write the superclass name after the subclass name, separated by a colon (:). The syntax format is as follows

class SomeClass: SomeSuperclass {
    // Class definition
}

Example

In the following example, we define a superclass StudDetails and then use the subclass Tom inherit it:

class StudDetails
{
    var mark1: Int;
    var mark2: Int;

    init(stm1:Int, results stm2:Int)
    {
        mark1 = stm1;
        mark2 = stm2;
    }

    func show()
    {
        print("Mark1:\(self.mark1), Mark2:\(self.mark2)")
    }
}

class Tom : StudDetails
{
    init()
    {
        super.init(stm1: 93, results: 89)
    }
}

let tom = Tom()
tom.show()

The output of the above program execution is as follows:

Mark1:93, Mark2:89

Powered by TorCMS (https://github.com/bukun/TorCMS).