10.3. Inheriting a super class and adopting protocols together

We are continuing with the previous example. Now let's expand on the idea. TAs are also students. A student can be either a graduate student or an undergrad student. Let's assume Alice is an undergrad TA. Let's see how we can write some code to define Alice:

First, we need to define a class Student that has property name and an initializer method to initialize the instance.

//super class Student...
class Student{
    var name: String
    init(name:String) {
        self.name = name
    }
}

Then we need to define the class UndergradTA that inherits Student class, and adopts or conforms TeachingAssistant protocol:

//UndergradTA inherits Student, and adopts/conforms TeachingAssistant protocol...

class UndergradTA: Student, TeachingAssistant{
    //own property course...
    var course:String
    
    //initializer for UndergradTA...
    init(name: String, course:String) {
        self.course = course
        super.init(name: name)
    }
    
    //defining adopted methods from TeachingAssistant...
    func biweeklyPayment() -> Double {
        return 1_500.00
    }
    
    func completeTraining() {
        print("\(name) completed the TA training.")
    }
    
    func rate() -> Int {
        return 5
    }
    
    // own describe method of UndergradTA...
    func describe(){
        print(
            """
            \(name) is a TA of \(course) course.
            They were rated \(self.rate())/5 by the professor.
            They are paid \(self.biweeklyPayment()) biweekly.
            """
        )
        self.completeTraining()
    }
}

Please note: a class can only inherit one superclass, but it can adopt as many protocols as it needs. So if there is a superclass to be inherited, the class is written as the first one after** : (like Student in this example) followed by the protocols separated by ,(comma).**

Here, in the above code, we can see UndergradTA the inherited Student class and adopted TeachingAssistant protocol. We have a new variable course in UndergradTA, so we write an init() method to initialize both the variable course and the variable name in the superclass Student.

Then we implement the adopted methods of the protocol TeachingAssistant. And finally we write UndergradTA's own method describe().

Let's create the TA alice:

Please try the whole thing in your own playground.

So now we have a basic understanding of how classes work with other classes and protocols. In iOS development, we will repeatedly face these concepts.

Reference code

Last updated

Was this helpful?