Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do multi-inheritance in swift?

Tags:

ios

swift

I need to implement a class (for convenience name it A) derived from UITableViewController and another(B) from UICollectionViewController. And there are a lot of things common, so I want to put them in class(C) and let A and B inherit C. Now A and B both have two class to inherit, but multiple inheritance is not allowed in swift, so how to implement this? I know there is no multi-inheritance allowed in swift, but I still want to know how to do the things I described above.

like image 806
Sherwin Avatar asked Nov 01 '16 13:11

Sherwin


People also ask

How can we apply multiple inheritance?

The only way to implement multiple inheritance is to implement multiple interfaces in a class. In java, one class can implements two or more interfaces. This also does not cause any ambiguity because all methods declared in interfaces are implemented in class.

Does iOS support multiple inheritance?

In this blog, we are going to learn about the multiple inheritances in Swift and their implementation in your iOS project. Swift is an Object-oriented programming language but it does not support multiple inheritances.

Can we have multiple inheritance?

Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with the same signature in both the superclasses and subclass.

How many types of inheritance are there in Swift?

Yes in Swift and Objective-c Single and Multilevel inheritance is supported. In swift and many other languages Multiple Inheritance is restricted by use of classes because of historical problems like deadly diamond and others ambiguities.In swift you can achieve the Multiple inheritance at some level by Protocols .


1 Answers

As stated in the comments by @Paulw11 is correct. Here is an example that involves A & B inheriting from C. Which I have named DogViewController and CatViewController (which inherits form PetViewController). You can see how a protocol might be useful. This is just an ultra basic example.

protocol Motion {
    func move()
}

extension Motion where Self: PetViewController {

    func move() {
        //Open mouth
    }

}

class PetViewController: UIViewController, Motion{
    var isLoud: Bool?

    func speak(){
        //Open Mouth
    }
}

class DogViewController:PetViewController {

    func bark() {

        self.speak()

        //Make Bark Sound
    }
}

class CatViewController: PetViewController {

    func meow() {

        self.speak()

        //Make Meow Sound


    }

}

//....

let cat = CatViewController()
cat.move()
cat.isLoud = false
cat.meow()
like image 183
Asdrubal Avatar answered Oct 03 '22 00:10

Asdrubal